How to skip one (2,3) value when getting json?

In the code below, you only need to get the second data - "dt": 1453798800 . When outputting data from foreach, it displays the entire list. And you need to display certain values. For example 2, 5 and 7.

{ "city":{ "id":542420, "name":"Krasnodar", "coord":{ "lon":38.976944, "lat":45.03278 }, "country":"RU", "population":0 }, "cod":"200", "message":0.0252, "cnt":2, "list":[ { "dt":1453712400, "temp":{ "day":-10.11, "min":-15.76, "max":-9.67, "night":-15.76, "eve":-11.65, "morn":-10 }, "pressure":1035.45, "humidity":99, "weather":[ { "id":600, "main":"Snow", "description":"небольшой снегопад", "icon":"13d" } ], "speed":4.66, "deg":25, "clouds":64, "snow":0.61 }, { "dt":1453798800, "temp":{ "day":-10.46, "min":-17.77, "max":-9.26, "night":-17.77, "eve":-12.58, "morn":-14.58 }, "pressure":1035.15, "humidity":96, "weather":[ { "id":600, "main":"Snow", "description":"небольшой снегопад", "icon":"13d" } ], "speed":3.41, "deg":68, "clouds":24, "snow":0.17 } ] } 

Php

  $data = @file_get_contents($url); $dataJson = json_decode($data); $arrayDays = $dataJson->list; // выводим данные foreach($arrayDays as $oneDay){ echo "Погода: " . $oneDay->weather[0]->description . "<br/>"; echo "Скорость ветра: " . $oneDay->speed . "<br/>"; echo "Давление: " . $oneDay->pressure . "<br/>"; } 

    1 answer 1

    Since the list field in your case is an array, you can select the necessary elements by the index

     var el0 = data.list[0]; var el1 = data.list[1]; //и т.д. 

    Or use the filter function and get an array with the necessary elements.

     var list = data.list.filter(function(element, index){ return index == 2 || index==5 || index==7; //выбираем элемент только с индексом 2,5 или 7 }) 

    UPDATE:
    Php array_filter example

     var_dump(array_filter($arr, function($v, $k) { return $k == 2 || $k ==5 || $k ==7; }, ARRAY_FILTER_USE_BOTH)); 

    eg:

     $arrayDays = array_filter($dataJson->list, function($v, $k) { return $k == 2 || $k ==5 || $k ==7; }, ARRAY_FILTER_USE_BOTH); 

    Please note: flag, the third parameter, added in version 5.6.0

    • I'm sorry, I understand this is JS? I am using PHP. - kate
    • @RomanPererva, you should indicate this in the tags :-) but the essence remains the same - you can either directly access the necessary elements by indices, or filter the array - Grundy
    • @RomanPererva, updated the answer - Grundy
    • Thanks for the quick answers. Updated the code in question. Can you please tell where to insert your solution for PHP. - kate
    • @RomanPererva, where you get the list - Grundy