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?
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?
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>";
}