studentJk studentJk - 4 months ago 23
PHP Question

Need help parsing JSON in PHP

I thought this would be pretty straight forward but I am clearly doing something wrong and I cannot decode this JSON correctly.

It either returns NULL or arrays but loads of them.

here is the JSON:

$json =
'[
{
"name":"apples",
"baskets":[10,20,30],
"unit_cost":0.26
},
{
"name":"bananas",
"baskets":[5,20,10,10],
"unit_cost":0.20
}
]';


and i'm doing

$products = json_decode($json, TRUE)


but when I do a var dump it returns this in the browser:

array(2) {
[0]=>
array(3) {
["name"]=>
string(6) "apples"
["baskets"]=>
array(3) {
[0]=>
int(10)
[1]=>
int(20)
[2]=>
int(30)
}
["unit_cost"]=>
float(0.26)
}
[1]=>
array(3) {
["name"]=>
string(7) "bananas"
["baskets"]=>
array(4) {
[0]=>
int(5)
[1]=>
int(20)
[2]=>
int(10)
[3]=>
int(10)
}
["unit_cost"]=>
float(0.2)
}
}


Is this correct? Seems as if a bunch of arrays are being created.

Also I want to be able to target the "baskets" to be able to add those values together.

Thanks for any help
`

Answer

Yea, that's right. If it's not the data you are expecting, maybe modify your JSON?

You have two hashes in your json:

{
  "name": "apples",
  "baskets": [10, 20, 30],
  "unit_cost": 0.26
}

and

{
    "name":"bananas",
    "baskets":[5,20,10,10],
    "unit_cost":0.20
}

Each of those parse into an array when you use the true flag to decode.

The value of baskets in your json is also an array, so naturally it'll be parsed that way,too.

To add the values of the baskest array, you can do this:

$products = json_decode($json, true);
$basketTotal = [];
foreach($products as $key => $product) {
  $basketTotal [$product["name"]] = array_sum($product["baskets"]);
}

Then, you can access each value like so:

$applesTotal = $basketTotal["apples"];

EDIT: Couldn't live with myself without using a loop, here. Updated basket total example.

Comments