简体   繁体   中英

Find maximum value in associative array

I have a associative array:

$users[0] = array('name' => 'Jim', 'depth' => '1', 'bk_id' => '9'); 
$users[1] = array('name' => 'Jill', 'depth' => '3', 'bk_id' => '10'); 
$users[2] = array('name' => 'Jack', 'depth' => '7', 'bk_id' => '17'); 

I would like to know a way of finding the array index with the maximum or greatest depth value?

Any suggestion is most appreciated.

Just iterate and look at the maximum value:

var max = 0, maxIndex = -1;
for(var i=0;i<users.length;i++) {
   if(parseInt(users[i].depth,10) > max) {
      max = users[i].depth;
      maxIndex = i;
   }
}
console.log("Your maximum depth is %d at index %d", max, maxIndex);

Since the question is unclear, here's how to find it with PHP.

foreach ($users as $index => $user) {
  if (!isset($maxdepth)) {
    $maxdepth = $user['depth'];
    $maxindex = $index;
  }
  else {
    if ($user['depth']) > $maxdepth) {
       $maxindex = $index;
       $maxdepth = $user['depth'];
    }
}
echo "Index: $maxindex";

From PHP:

$index = 0;
$max = 0;

for ($i = 0; $i < count($users); $i++) {
    if ($users[$i]['depth'] > $max) {
        $max = $users[$i]['depth'];
        $index = $i;
    }
}

echo $users[$index]['name'] . ' has the greatest depth.';

您既可以遍历所有键值对,每次都查看深度值,也$users使用诸如sort_func(){ return a.depth - b.depth}的自定义排序功能sort_func(){ return a.depth - b.depth}来对$users数组进行排序。

Using native sort function?

function getDeepestItem(arr)
{
    arr.sort(function(a,b){return a['depth'] < b['depth'];});
    return arr[0]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM