1

This are my array

$items = array( "100"=>
    array(
        'id' => 15,
        'category' => array('id'=>'100010'),
        'description' => array('type'=>'Drink'),
    ),
    "101"=>
    array(
        'id' => 13,
        'category' => array('id'=>'100055'),
        'description' => array('type'=>'Fruit'),
    ),
    "102"=>
    array(
        'id' => 21,
        'category' => array('id'=>'100002'),
        'description' => array('type'=>'Vege'),
    )
);

$soryBy = array(array('id'=>'100055'),array('id'=>'100002'),array('id'=>'100010'));

What are the approach to sort the $items category according to $soryBy? Is there any existing php function i can use?? Thanks

1 Answer 1

2

The first thing you are going to want to do is to flatten out your $sortBy array

$sortBy = array_map(function($a) { return $a["id"]; }, $sortBy);

Then you can use usort with a closure

usort($items, function($a, $b) use ($sortBy) {
      return array_search($a["category"]["id"], $sortBy) - array_search($b["category"]["id"], $sortBy);
});

Note this solution should work for PHP 5.3 and above.

2
  • I getting error array_map(): Argument #2 should be an array what are the issue, but i create a manual flatten array in usort it works great!
    – Eric
    Jul 8, 2013 at 6:18
  • i think the issue is that the second parameter to array_map should be $soryBy not $sortBy based on your code
    – Orangepill
    Jul 8, 2013 at 6:25

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.