Get a specific recurring value from JSON array using PHP foreach loop -
i have following json array:
{"key1":"example1","key2":"example2","key3":"example3","key4":"example4","key1":"example5","key2":"example6","key3":"example7","key4":"example8","key1":"example9","key2":"example10","key3":"example11","key4":"example12"}
using php possible display specific recurring value, example if wanted display "key1" in foreach loop return following:
example1 example5 example9
appreciate tips on use this, thanks.
you aren't going able using json_encode because it's not valid json. (keyspace collision)
you going need assemble object manually.
you might consider creating individual items, using implode(). can prepend , append { , }.
<?php $jsonobject='{"key1":"example1","key2":"example2","key3":"example3","key4":"example4","key1":"example5","key2":"example6","key3":"example7","key4":"example8","key1":"example9","key2":"example10","key3":"example11","key4":"example12"}'; $jsonarray = array_map( function($array){ $keyvalue=explode(":",$array); return array("key"=>substr($keyvalue[0],1,-1),"value"=>substr($keyvalue[1],1,-1)); }, explode( ",", substr($jsonobject,1,-1) ) ); foreach($jsonarray $object){ $output[$object['key']][]=$object['value']; } echo implode("\n",$output['key1']); ?>
Comments
Post a Comment