Reputation: 1660
I will use my specific example to explain:
My array consists of values that represent the most specific category that a product belongs to, however it may belong to different branches on a category tree each branch is then represented by an array value which is itself an array of all of the parent categories that the category belongs to.
I would like to find the longest branch E.g the category that a product belongs to which has the largest number of parent categories. for example:
var_dump($my_breadcrumbs);
array(
[0] => array( [0] => Object Category , [1] Object Category)
[1] => array( [0] => Object Category , [1] Object Category, [2] Object Category)
I want to move the array element with the largest number of values to position 0
I can do this through a series of tests but I want to see if there is a way to use php's sort.
Upvotes: 0
Views: 1618
Reputation: 7795
usort($my_breadcrumbs, function ($a, $b){
return count($b) - count($a);
});
Upvotes: 4
Reputation: 224942
You don’t need to sort just to get the longest one; array_reduce
can act like max
with a key:
$longest = array_reduce($my_breadcrumbs, function($a, $b) {
return count($b) > count($a) ? $b : $a;
});
Upvotes: 1