user3187651
user3187651

Reputation: 57

get json value from php loop

how can I get the same results/values in one loop rather than two?

$json = file_get_contents($url) 
$data = json_decode($json, true);


$desc = $data["descriptions"];
$assets = $data["assets"];

foreach ($assets as $assItem) {
    echo $assItem["assetid"];
}


foreach($desc as $descItem) {
    echo descItem["name"];
}

I've tried something like

$json = file_get_contents($url);
$data = json_decode($json, true);

foreach ($data as $item) {
    echo $item["assets"]["assetid"];
    echo $item["descriptions"]["name"];
}

pastebin to the json: https://pastebin.com/raw/uA9mvE2e

Upvotes: 1

Views: 48

Answers (1)

segFault
segFault

Reputation: 4054

You could do something like:

$json = file_get_contents($url);
$data = json_decode($json, true);

foreach ($data['assets'] as $k => $item) {
    echo $item["assetid"];
    echo $data["descriptions"][$k]["name"];
}

This assumes that $data['assets'] and $data['descriptions'] share the same indices.

Upvotes: 1

Related Questions