0
$myarray=
Array ( [0] => Array ( [id] => 4
                       [name] => ABC
                       [point] => 2111 
      ) [1] => Array ( [id] => 5
                       [name] => XYZ 
                       [point] => 1305 )




$points = array_map(function($myarray) {
        return $store[0];
    }, $myarray);

 $maxpoint=max($points)

But how will I get the id of the person with max points? Basically I need to get the row (or inner array) where the point is maximum.

How is it possible to perform mysql like sorting in this array with only using php?

Please Help

6
  • 1
    php.net/manual/en/function.uasort.php Commented Jan 29, 2016 at 19:23
  • 1
    Possible duplicate of How can I sort arrays and data in PHP? Commented Jan 29, 2016 at 19:33
  • 1
    @Don'tPanic: I would agree if they had asked how to sort, though that may be the best way. Commented Jan 29, 2016 at 19:35
  • @AbraCadaver I'm not trying to be argumentative, but didn't they? "How is it possible to perform mysql like sorting in this array with only using php?" Commented Jan 29, 2016 at 19:39
  • @Don'tPanic: Yes, I guess I could have read the title, sorry :-( Commented Jan 29, 2016 at 19:40

2 Answers 2

2

You can combine them but here are the general steps:

// extract all points and get the max()
$maxpoint = max(array_column($myarray, 'point'));

// get the key of the array with the max points
$key = array_search(array_column($myarray, 'point'), $maxpoint);

// get the id using the key
$id = $myarray[$key]['id'];

// or get the entire array
$result = $myarray[$key];

Another option is to sort on point descending so that it will always be index 0:

array_multisort(array_column($myarray, 'point'), SORT_DESC, $myarray);

echo 'id ' . $myarray[0]['id'] . ' has ' . $myarray[0]['point'] . ' points';
Sign up to request clarification or add additional context in comments.

Comments

0

Nothing wrong with the accepted answer, (it's great, actually) but if all you need is the person with the highest score, you don't need to sort the array. You can just iterate it and keep track of the highest pointer as you go.

$person['point'] = 0; // starting value

foreach ($myarray as $row) {
    if ($row['point'] > $person['point']) {
        $person = $row; // replace $person with new highest points person
    }
}

Comments

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.