How to get all pid and styles attribute from following json data with minimum loop in php
{"general":{"note":{"display":false}},"elements":{"the-1":{"index":1,"src":"shirt1.png","pid":"pid-3563130","angle":0,"styles":"background:transparent;top:51.80000305175781px;left:122px;width:80px;height:80px;","background":"transparent","pos":{"top":51.80000305175781,"left":122},"size":{"width":80,"height":80},"details":{"other":""}},"the-2":{"index":2,"src":"shirt2.png","pid":"pid-132002","angle":0,"styles":"background:transparent;top:44.80000305175781px;left:155px;width:80px;height:80px;","background":"transparent","pos":{"top":44.80000305175781,"left":155},"size":{"width":80,"height":80},"details":{"other":""}}}}
Thanks
$str = '{"general":{"note":{"display":false}},"elements":{"the-1":{"index":1,"src":"shirt1.png","pid":"pid-3563130","angle":0,"styles":"background:transparent;top:51.80000305175781px;left:122px;width:80px;height:80px;","background":"transparent","pos":{"top":51.80000305175781,"left":122},"size":{"width":80,"height":80},"details":{"other":""}},"the-2":{"index":2,"src":"shirt2.png","pid":"pid-132002","angle":0,"styles":"background:transparent;top:44.80000305175781px;left:155px;width:80px;height:80px;","background":"transparent","pos":{"top":44.80000305175781,"left":155},"size":{"width":80,"height":80},"details":{"other":""}}}}';
$arr = json_decode($str, true);
foreach ($arr['elements'] as $element) {
echo 'pid: ' . $element['pid'] . '<br />';
echo 'styles: ' . $element['styles'] . '<br />';
}
use json_decode function in PHP to get assosiative array.
<?php
$myJson = '{"general":{"note":{"display":false}},"elements":{"the-1":{"index":1,"src":"shirt1.png","pid":"pid-3563130","angle":0,"styles":"background:transparent;top:51.80000305175781px;left:122px;width:80px;height:80px;","background":"transparent","pos":{"top":51.80000305175781,"left":122},"size":{"width":80,"height":80},"details":{"other":""}},"the-2":{"index":2,"src":"shirt2.png","pid":"pid-132002","angle":0,"styles":"background:transparent;top:44.80000305175781px;left:155px;width:80px;height:80px;","background":"transparent","pos":{"top":44.80000305175781,"left":155},"size":{"width":80,"height":80},"details":{"other":""}}}}';
$myArray = json_decode($myJson,true);
$myInnerArray = $myArray['elements'];
$styles = array();
foreach($myInnerArray as $element)
$styles[] = $element['styles'];
print_r($styles);
?>
PHP has great abilities to handle json.
Let's assume the JSON string you've posted above is stored in a PHP variable $myJSON
.
So we can easily store an associative array of these values into $myJSONArray
like so:
$myJSONArray = json_decode( $myJSON, true );
So, now we just loop through:
foreach( $myJSONArray['elements'] as $arr => $key )
echo( "A PID: " . $key['pid'] . "\n" );
See it in action on Codepad.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With