0

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.

2 Answers 2

4
usort($my_breadcrumbs, function ($a, $b){
    return  count($b) - count($a);
});
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

I wish I could checkmark the both of you because both work for my very specific example however I think that being that the title's first word is sort Pe de Leao is more appropriate. I just wanted to give props to you as well.

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.