B
B
bone_games2021-02-03 14:19:54
PHP
bone_games, 2021-02-03 14:19:54

How to iterate json array?

Hello, I can’t sort through the json array.
It is necessary to pull out all the id and name of all streets (street) for autocompletion.
I get such a json array with api

[{"city":{
"id":"123",
"name":"название города"
},
"streets":[
{
"id":"1",
"name":"имя"
},
{
"id":"2",
"name":"имя"
},
]},

{"city":{
"id":"1234",
"name":"название города"
},
"streets":[
{
"id":"3",
"name":"название улицы"
},
{
"id":"4",
"name":"название улицы"
},
]
}]


You need to somehow pull it into something like this cycle
foreach ($items as $item) {
          
          $json[] = array(
            'id'       => $item['id],
            'name'     =>$item['name']
);
          
        }

Maybe poke wherever you can see similar examples
Thanks in advance to those who respond.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey Sokolov, 2021-02-03
@bone_games

// $api_json = ''; //  тут текст из ответа API
$data = json_decode($api_json, true);
$all_streets = [];

foreach ($data as $city) {
    $city_name = $city['name'];
    $city_id = $city['id'];
    $city_streets = $city['streets'];
    foreach ($city_streets as $street) {
        $all_streets[] = [
            'id' => $street['id'],
            'name' => $street['name'],
            // может, и параметры города сюда же?
            'city' => $city_name,
            'city_id' => $city_id,
        ];
    }
}

S
Swert, 2021-02-03
@swert-tech

If I understand you correctly

$items = json_decode([], true);

foreach ($items as $item) {
    $result = [
        'id'    => $item['id'],
        'name'  => $item['name']
    ];

    var_dump($result);
}

A
Alexey, 2021-02-22
@alexgl2004

$json_arr = json_decode($json_string,1);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question