0

I would like to get the highest value (y) from the following json-file.

   [{
     "name": "Time",
     "data": ["20:40", "20:45", "20:50"]
     },
     {
     "name": "Values",
     "data": [{
               "y": 5774,
               "v1": "Test1",
               "v2": "20:40"
              },
              {
               "y": 5555,
               "v1": "Test2",
               "v2": "20:45"
              },
              {
               "y": 5235,
               "v1": "Test3",
               "v2": "20:50"
              }]
            }]

Tried it with max()

$json_data = file_get_contents('file.json');
$json = json_decode($json_data, true);
$max_value = max($json["data"]);

echo $max["y"];

but I'm not getting any result...

1
  • you use wrong variable maybe should be $max_value['y'] non $max['y'] Commented Mar 12, 2016 at 21:07

4 Answers 4

1

The following will retrieve the largest y value:

<?php
    $json_data = file_get_contents('a.json');
    $json = json_decode($json_data, true);
    $max_value = max($json[1]["data"]);

    echo $max_value['y'];
?>

And the following will retrieve the array with the largest y value:

<?php
$json_data = file_get_contents('a.json');
$json = json_decode($json_data, true);
$max_value = max($json[1]["data"]);

print_r($max_value);
?>

The problem with your script was you were trying to access a non-existent array on line 3 and you weren't echoing out the $max_value array correctly.

Warning

The above code only works because OP's JSON when converted to an array has the element he wants to order his array by as the first indexed value.

So like @MatsLindh stated below in the comments, if you had a value with the key of 'x' instead of 'y', no matter where it's located in the JSON provided it's still the lowest key value placing it as the first indexed value in the array when converted from JSON to an array.

You can still have mix-matched values in the JSON provided as long as the element you want to order by has the lowest value key placing it as the first element indexed in the array. For example:

   [{
     "name": "Time",
     "data": ["20:40", "20:45", "20:50"]
     },
     {
     "name": "Values",
     "data": [{
               "y": 5774,
               "v1": "Test1",
               "v2": "20:40",
               "Z" : 8000
              },
              {
               "y": 5555,
               "v1": "Test2",
               "v2": "20:45",
               "Abc": 6754
              },
              {
               "y": 5235,
               "v1": "Test3",
               "v2": "20:50",
               "v3": 6594
              }]
            }]

If the above JSON were passed through my first function it would return the desired result the OP was looking for, however.

   [{
     "name": "Time",
     "data": ["20:40", "20:45", "20:50"]
     },
     {
     "name": "Values",
     "data": [{
               "y": 5774,
               "v1": "Test1",
               "v2": "20:40",
                "a": 897
              },
              {
               "y": 5555,
               "v1": "Test2",
               "v2": "20:45"
              },
              {
               "y": 5235,
               "v1": "Test3",
               "v2": "20:50"
              }]
            }]

With this set of JSON, the element with the key "a" messes the count order up since it's placed at the beginning of the array.

Conclusion

If you know that the first value of the array generated from the JSON will always be what you want to count by then my code is fine. Otherwise it's better for you to use @MatsLindh's solution.

Sign up to request clarification or add additional context in comments.

6 Comments

Your answer is too good. Just add print_r($max_value['y']); and it will be perfect because he wants value for Y only, not the array.
@YousafHassan Point taken. Revised answer. However I saw it best to use echo instead of print_r since $max_value['y'] always seems to be a string.
You are right, echo does the job, and yes i have voted up for your answer because its better than all others including mine.
But this is not correct - the only reason why this works, is because the associative arrays are of the exact same size (and that the value you want to compare is the first value in the associative array). If there suddenly is one extra key in one of the assocative arrays (or the feed returns them in a different sequence - after all, they're just keys pointing to values), such as "x": 123 in the last element - then that will always be returned, regardless of the value of y.
@MatsLindh Good point. Updated answer to include warning. However I still feel as if my answer was the best for OP since he/she had provided an example JSON set that follows a certain format.
|
0

The problem is that your json_decoded data isn't all in array form, but includes STD objects as well so another way to find the maximum value in your case is by using following algo.

$json_data = file_get_contents('file.json');
$json = json_decode($json_data, true);
$max_value = null;
foreach($json[1]->data as $dt){
    if($dt->y > $max_value)
        $max_value = $dt->y;
}
echo $max_value; // There it will output the highest value!

Comments

0

You can look this array in php format by var_dump function

$json_data = file_get_contents('file.json');
$json = json_decode($json_data, true);
$max_value = max($json["data"]);
var_dump($max_value);

and you need don't use max because this last element in array you need check exist key name = values for get values by foreach or array_map for analise you array in exist key name = values for exampel

$json_data = file_get_contents('file.json');
$json = json_decode($json_data, true);
foreach($json as $_js) {
   if($_js['name'] != 'Values') {
      continue;
   }
   foreach($_js['data'] as $__js) {
       echo $__js['y']; // or push to temporary variable
   }
}

Comments

0

Since you're really trying to get the max value of a certain column in the array (doing just max($json[1]['data']) doesn't make sense by itself, as each element in that array is an associative array itself), you'll have to pick the values you want to find the maximum value of first:

$max_value = max(array_column($json[1]["data"], "y"));

This will extract each value from the y column of each element in the $json["data"] array, and return the largest value present (through max).

array_column was added in PHP 5.5, but you can emulate it through a small helper function if you're on an older version:

function array_column($array, $column) {
    $ret = array();
    foreach ($array as $elem) {
        $ret[] = $elem[$column];
    }
    return $ret;
}

3 Comments

$json['data'] not exist because he have array objects in context question
why adding [1] after, maybe before adding [1][data]
@Naumov Added it in the right place in the text, in the wrong place in the code. :-) You're my human compiler!

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.