-4

I have this string:

[[{"id":"1"},{"qty":"2"}],[{"id":"2"},{"qty":"1"}],[{"id":"4"},{"qty":"3"}],[{"id":"5"},{"qty":"1"}]]

How can I turn it into a multidimensional PHP Array and loop through each id?

zessx
  • 68,042
  • 28
  • 135
  • 158
jQuerybeast
  • 14,130
  • 38
  • 118
  • 196
  • possible duplicate of [How to convert JSON string to array](http://stackoverflow.com/questions/7511821/how-to-convert-json-string-to-array) – user1978142 Jul 11 '14 at 08:02

3 Answers3

0

This is a JSON encoded string, so just use json_decode

Maxim Krizhanovsky
  • 26,265
  • 5
  • 59
  • 89
0

This is a JSON object. Just use json_decode().

Ghigo
  • 2,312
  • 1
  • 18
  • 19
0

You can use json_decode($json) in order to do this, using it allows you to obtain an array of objects or if you call json_decode with the second parameter set to false json_decode($json,TRUE) you'll obtain just an array.

Here is an example:

$str = '[{"id":"1","qty":"2"},{"id":"2","qty":"1"},{"id":"4","qty":"3"},{"id":"5","qty":"1"}]';
$data = json_decode($str);
foreach ($data as $block) {
    echo $block->id."::".$block->qty."<br>";
}

$data = json_decode($str,TRUE);

foreach ($data as $block) {
    echo $block['id']."::".$block['qty']."<br>";
}
Cristofor
  • 2,077
  • 2
  • 15
  • 23