There is a one-dimensional JSON array

{"city":{"id":2013159,"name":"London", "list": [ {"dt":1459360800,"main":{"temp":-6.55,"temp_min":-6.55,"temp_max":-2.34},"weather":[{"id":800,"main":"Clear","description":"ясно"}], {"dt":1459425600,"main":{"temp":-8.55,"temp_min":-10.55,"temp_max":-4.34},"weather":[{"id":700,"main":"Cloud","description":"Облака"}], {"dt":1459458000,"main":{"temp":-10.56,"temp_min":-15.55,"temp_max":-8.34},"weather":[{"id":600,"main":"Clear","description":"ясно"}] ]} 

The dt object data is constantly changing "dt": 1459425600 then "dt": 1459458000. How to output the data in PHP corresponding to a specific dt, for example, I want to derive from this array only the data that corresponds to "dt": 1459425600 is:

 {"dt":1459425600,"main":{"temp":-8.55,"temp_min":-10.55,"temp_max":-4.34},"weather":[{"id":700,"main":"Cloud","description":"Облака"}] 

ps do not suggest using an index, only through dt, which I will indicate

  • decode json_decode into an array and further in the loop select the desired data. What is the problem then? - vitidev
  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

1 answer 1

  1. The array is never one-dimensional.
  2. JSON has errors
  3. For such purposes it is better to use MySQL or other databases.

The answer itself:

Php

 function getRowByDt($object, $dt) { foreach($object['city']['list'] as $item) { if($item['dt'] == $dt) { return $item; } } return NULL; } 
  • It is not clear, it does not work, I tried to print it using echo (getRowByDt ()); displays an error: PHP: Warning: Missing argument (1) for getRowByDt (), called in getForecast.php (on line 96) PHP Warning: Missing argument (2) for getRowByDt (), (called) PHP Notice: Undefined variable: getForecast.php on line 97 - mocart
  • probably because you need to pass an object (array) $ object of decoded JSON and $ dt string to search for. Learn more about the features: php.net/manual/ru/functions.user-defined.php And about the arguments: php.net/manual/ru/functions.arguments.php - Screaming Voices