Split array based on a property

I have an array that contains a query and gives me values like


[0] => stdClass Object ( [id] => 233 [title] => Login [path] => login [link] => index.php?option=com_users&view=login [parent_id] => 1 [level] => 1 [lft] => 11 ) 
[1] => stdClass Object ( [id] => 238 [title] => Sample Sites [path] => sample-sites [link] => index.php?option=com_content&view=article&id=38 [parent_id] => 1 [level] => 1 [lft] => 259 )

Giving those and taking in consideration that I don´t know the values of lft as they are random how can I select from the array the object with the lowest number in lft?

Just to make my question a little be clearer as I don´t know if I´m making any sense, if I have an array with values 6, 1, 3, 10, 25 if I want to access the 1 in this case the index is 1 so I can just go $array[1]; but what if I want to access 1 but don´t know the index, all I know is that I need the lowest number in the array which in this case turns out to be 1.

Look at each object in the array, keep track of the smallest you’ve seen, then at the end you’ll know which had the smallest value.

$min = 9999;
$min_index = 0;
foreach ($array as $index => $object) {
    if ($object->lft < $min) {
        $min = $object->lft;
        $min_index = $index;
    }
}

$one_you_want = $array[$min_index];

Alternatively, you could use [fphp]usort[/fphp] and simply get the first element in the array. :slight_smile:


function sortByLft(stdClass $a, stdClass $b){
  if($a->lft === $b->lft){
    return 0;
  }
  return $a->lft < $b->lft ? -1 : 1 ;
}

usort($collection, 'sortByLft');

$lowestLft = $collection[0];

Off Topic:

The return values from the sorting function needn’t be exactly -1, 0 or 1. The body of that function could be reduced to simply:

return $a->lft - $b->lft;

Well I never, more things to investigate.

Cheers Salathe. :slight_smile:

If there are many elements in this array (not that there probably are), the linear search will be much faster than a quicksort.

There could be 1 or many, also each index of the array has a lot more properties, I will try all the suggestions and let you know how it went.