4

Is there an easy way to sort an array with a variable array made for this task? For example:

$fruits [
   'Apple' => '12',
   'Cherry' => '10',
   'Lemon' => '34', 
   'Peach' => '6'
]

$order [
   1 => 'Peach',
   2 => 'Other',
   3 => 'Lemon',
   4 => 'Other2',
   5 => 'Apple',
   6 => 'Cherry',
   7 => 'Other3'
]

I'd like to return this kind of array:

$ordered_fruits [
   'Peach' => '6',
   'Lemon' => '34',
   'Apple' => '12',
   'Cherry' => '10'
]
2

4 Answers 4

11

make it with php functions:

$new = array_filter(array_replace(array_fill_keys($order, null), $fruits));
3
  • how funny the PHP functions are....., We did a lot of code and you did it with some library functions. Commented Apr 27, 2016 at 10:23
  • Yes, it's library has so many funs that if not the SO i forgot half of them :) Commented Apr 27, 2016 at 10:25
  • This is superb, it works perfectly for what I want to achieve. Commented May 22, 2022 at 11:29
5
$ordered_fruits = array();
foreach($order as $value) {

   if(array_key_exists($value,$fruits)) {
      $ordered_fruits[$value] = $fruits[$value];
   }
}
1
  • 1
    great, i took little bit time to give answer. Commented Apr 27, 2016 at 10:04
3

try this :

$fruits = array(
   'Apple' => '12',
   'Cherry' => '10',
   'Lemon' => '34', 
   'Peach' => '6'
);

$order = array(
   1 => 'Peach',
   2 => 'Other',
   3 => 'Lemon',
   4 => 'Other2',
   5 => 'Apple',
   6 => 'Cherry',
   7 => 'Other3'
);

$result = array();
foreach ($order as $key => $value) {
  if ( array_key_exists($value, $fruits) ) {
    $result[$value] = $fruits[$value];
  }
}
print_r($result );
0
1

Technique of sorting:

$result = array();

foreach($order as $value){
    if(array_key_exists($value, $fruits)){
        $result[$value] = $fruits[$value];
    }
}

Result

print_r($result);

Array
(
    [Peach] => 6
    [Lemon] => 34
    [Apple] => 12
    [Cherry] => 10
)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.