-3

noob here! How I can get 'qty' value to print only 0 with json and php from:

{"XXXXXX":[],"XXXXXX":[],"total":[{"assetref":"","qty":0,"raw":0}]}

I've tried this

$m = json_encode('{"XXXXXX":[],"XXXXXX":[],"total":[{"assetref":"","qty":0,"raw":0}]}')
$multi = json_decode($m, true);
echo $multi->{'qty'};

And not work

3 Answers3

0

You already have JSON string hence you must not use json_encode:

$multi = json_decode('{"XXXXXX":[],"XXXXXX":[],"total":[{"assetref":"","qty":0,"raw":0}]}', true);
echo $multi['total'][0]['qty'];
cn007b
  • 16,596
  • 7
  • 59
  • 74
0

json_encode is used to create a JSON string from a variable.

You already have a JSON string so instead of using $m = json_encode(json_string) you could simply say that $m = json_string.

Also you are missing one level of depth (no reference to total) while trying to access the qty variable.

(Please notice that total is an array which contains one object, which then contains qty)

Try that:

$m = '{"XXXXXX":[],"XXXXXX":[],"total":[{"assetref":"","qty":0,"raw":0}]}';
$multi = json_decode($m, true);
echo $multi['total'][0]['qty'];
Ezenhis
  • 997
  • 9
  • 14
0

json_encode encodes a array into a string, you're trying to encode a string.

Use json_decode on your string so it converts to array.

$m = json_decode('{"XXXXXX":[],"XXXXXX":[],"total":[{"assetref":"","qty":10,"raw":0}]}');
$qty = $m->total[0]->qty;
echo $qty;
Bob
  • 41
  • 8