从php中的json数组中找到最大的价值

时间:2016-11-27 16:32:34

标签: php arrays json

我正在使用以下代码显示JSON中每个字符的时间。但问题是有重复的因素。我只想为每个选择最高值。

例如,s的最高值为85t84

我尝试了max()函数,但只返回了最大值:

<?php
  $speedArray =  json_decode('[{"key":"e","time":35},{"key":"s","time":43},{"key":"t","time":39},{"key":"t","time":84},{"key":"s","time":85},{"key":"s","time":27},{"key":"t","time":80}]', true);

  foreach ($speedArray as $timing) {
     echo $timing['key'].$timing['time']."<br/>";
  } 
?>

2 个答案:

答案 0 :(得分:3)

首先,我将创建一个$key映射,并将所有值都放在数组中:

<?php
$speedArray =  json_decode('[{"key":"e","time":35},{"key":"s","time":43},{"key":"t","time":39},{"key":"t","time":84},{"key":"s","time":85},{"key":"s","time":27},{"key":"t","time":80}]', true);
$keys = array();
foreach ($speedArray as $key) {
    $keys[$key["key"]][] = $key["time"];
}
print_r($keys);

输出结果为:

Array
(
  [e] => Array
    (
      [0] => 35
    )

  [s] => Array
    (
      [0] => 43
      [1] => 85
      [2] => 27
    )

  [t] => Array
    (
      [0] => 39
      [1] => 84
      [2] => 80
    )
)

现在更容易获得最好的。使用max()函数:

<?php
$speedArray =  json_decode('[{"key":"e","time":35},{"key":"s","time":43},{"key":"t","time":39},{"key":"t","time":84},{"key":"s","time":85},{"key":"s","time":27},{"key":"t","time":80}]', true);
$keys = array();
foreach ($speedArray as $key) {
    $keys[$key["key"]][] = $key["time"];
}
foreach ($keys as $key => $vals) {
    echo "{$key}: " . max($vals) . "\n";
}

我得到了这个输出:

e: 35
s: 85
t: 84

演示:http://ideone.com/g4zULB

答案 1 :(得分:1)

使用单个循环和max函数获取每个键的 max 值:

$speedArray =  json_decode('[{"key":"e","time":35},{"key":"s","time":43},{"key":"t","time":39},{"key":"t","time":84},{"key":"s","time":85},{"key":"s","time":27},{"key":"t","time":80}]', true);
$result = [];

foreach ($speedArray as $v) {
    (isset($result[$v['key']]))? 
            $result[$v['key']] = max($result[$v['key']], $v['time']) 
            : $result[$v['key']] = $v['time'];
}

print_r($result);

输出:

Array
(
    [e] => 35
    [s] => 85
    [t] => 84
)