GCW
GCW

Reputation: 312

PHP - Sort array with another array

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'
]

Upvotes: 4

Views: 6589

Answers (4)

Ranjit Shinde
Ranjit Shinde

Reputation: 1130

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 );

Upvotes: 3

Murad Hasan
Murad Hasan

Reputation: 9583

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
)

Upvotes: 1

splash58
splash58

Reputation: 26153

make it with php functions:

$new = array_filter(array_replace(array_fill_keys($order, null), $fruits));

Upvotes: 11

Kanishka Panamaldeniya
Kanishka Panamaldeniya

Reputation: 17576

$ordered_fruits = array();
foreach($order as $value) {

   if(array_key_exists($value,$fruits)) {
      $ordered_fruits[$value] = $fruits[$value];
   }
}

Upvotes: 5

Related Questions