Gijo Varghese
Gijo Varghese

Reputation: 11780

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

Upvotes: 2

Views: 684

Answers (2)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Getting max values for each key with a single loop and max function:

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

THe output:

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

Upvotes: 1

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

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

Upvotes: 3

Related Questions