4

I'm looking for shortest way to find the object which contains highest sort value.

array(5) {
  [0]=>
  object(stdClass)#212 (3) {
    ["id"]=>
    int(1)
    ["display_name"]=>
    string(8) "Activate"
    ["sort"]=>
    int(1)
  }
  [1]=>
  object(stdClass)#213 (3) {
    ["id"]=>
    int(2)
    ["display_name"]=>
    string(7) "Cutting"
    ["sort"]=>
    int(2)
  }
  [2]=>
  object(stdClass)#214 (3) {
    ["id"]=>
    int(3)
    ["display_name"]=>
    string(6) "Sewing"
    ["sort"]=>
    int(3)
  }
  [3]=>
  object(stdClass)#215 (3) {
    ["id"]=>
    int(4)
    ["display_name"]=>
    string(9) "Finishing"
    ["sort"]=>
    int(4)
  }
  [4]=>
  object(stdClass)#216 (3) {
    ["id"]=>
    int(5)
    ["display_name"]=>
    string(10) "Deactivate"
    ["sort"]=>
    int(5)
  }
}

Below is my practicing but I think it is complex and long of code.

// $gateways is the array contains a list of objects.

// find max sort value in array first
$max = max( array_map(function( $row ){ return $row->sort; }, $gateways) );

// then find in array object with sort value is equal to $max value
$filter = array_filter($gateways, function($row) use ($max){ 
  return $max == $row->sort;
});

if(count($filter)){
  $finalResult = array_shift($filter);
}

Is there shorter way to do this like reduce in Javascript?

Thanks.

1

1 Answer 1

8

Finally I did it.

$result = array_reduce($gateways, function($a, $b){
  return $a ? ($a->sort > $b->sort ? $a : $b) : $b;
});
Sign up to request clarification or add additional context in comments.

1 Comment

This answer is fundamentally different from what your coding attempt does. Sorting is not the same thing as filtering and the time complexity is different 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.