James Aniszt James Aniszt -4 years ago 91
JSON Question

PHP | Getting JSON data from URL and putting it to a array shows only 1 item?

I am trying to grab some JSON data from URL and then trying to put it into a array and then echo it out to a webpage. What am I doing wrong?

$data = json_decode($json, true);

$items = $data["rgDescriptions"];

foreach($items as $item){
$data2 = [
'market_hash_name' => $item["market_hash_name"],
'price' => 0,
'permission' => 'both_side'
];
}

echo json_encode($data2);

Answer Source

You are overwriting your $data2 variable every time the loop goes through. Declare you array outside of the loop and add each element in a new key of your array.

$data = json_decode($json, true);

$items = $data;
$data2 = [];

foreach($items as $item){
    $data2[] = [
    'market_hash_name' => $item["market_hash_name"],
    'price' => 0,
    'permission' => 'both_side'
    ];
}

echo json_encode($data2);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download