Gijo Varghese Gijo Varghese - 11 days ago 5
JSON Question

Find greatest value from json array in php

I'm using the following code to display the time for each character from a JSON. But the problem is there are repeated elements. I only want to select the highest value for each.

For example, highest value of

s
is
85
,
t
is
84
.

I tried the
max()
function, but only returning largest of all:

<?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/>";
}
?>

Answer

First I would create a $key mapping and put all the values as array:

<?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);

The output would be:

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

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

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

Now it is easier to get the greatest of it. Using the max() function:

<?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";
}

I get to this output:

e: 35
s: 85
t: 84

Demo: http://ideone.com/g4zULB