Answer the question
In order to leave comments, you need to log in
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":"название улицы"
},
]
}]
foreach ($items as $item) {
$json[] = array(
'id' => $item['id],
'name' =>$item['name']
);
}
Answer the question
In order to leave comments, you need to log in
// $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,
];
}
}
If I understand you correctly
$items = json_decode([], true);
foreach ($items as $item) {
$result = [
'id' => $item['id'],
'name' => $item['name']
];
var_dump($result);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question