$data='[{"type":"browsers","list":[{"key":"mobilesafari","value":3},{"key":"safari","value":1},{"key":"chrome","value":1}],"cardinality":3},{"type":"countries","list":[{"key":"US","value":3},{"key":"KR","value":1},{"key":"BR","value":1}],"cardinality":3},{"type":"languages","list":[{"key":"en-us","value":3},{"key":"pt-br","value":1},{"key":"ko-kr","value":1}],"cardinality":3},{"type":"organisations","list":[{"key":"Williams-Sonoma","value":1},{"key":"Verizon Wireless","value":1},{"key":"SK Telecom","value":1},{"key":"Oi Velox","value":1},{"key":"CenturyLink","value":1}],"cardinality":5},{"type":"platforms","list":[{"key":"iphone","value":2},{"key":"win8","value":1},{"key":"mac108","value":1},{"key":"ipad","value":1}],"cardinality":4}]';
if( !function_exists('pre') ){/* utility function for formatted output - aids debugging */
function pre( $data ){
echo '<pre>',print_r( $data, 1 ),'</pre>';
}
}
if( !function_exists('createobject') ){
function createobject( $data=false ){
try{
if( !$data )throw new Exception('Bad value supplied for input data');
/* decode the supplied data */
$json=json_decode( $data );
/* re-use the variable but reassign as an object */
$data=new stdClass;
/* Iterate through the json data and construct out output object */
foreach( $json as $obj ){
try{
/*
A temporary array to store each list item
~ could potentially use `array_map` here
*/
$tmp=new stdClass;
foreach( $obj->list as $i => $item ){
$tmp->{$item->key}=$item->value;
}
/* Assign new property to output object */
$data->{$obj->type}=$tmp;
}catch( Exception $e ){
continue;
}
}
return $data;
}catch( Exception $e ){
echo $e->getMessage();
}
}
}
/* To use new object */
$obj=createobject( $data );
pre( $obj );
pre( $obj->browsers );
pre( $obj->organisations );
echo $obj->languages->{'en-us'}; //3
这将输出:
stdClass Object
(
[browsers] => stdClass Object
(
[mobilesafari] => 3
[safari] => 1
[chrome] => 1
)
[countries] => stdClass Object
(
[US] => 3
[KR] => 1
[BR] => 1
)
[languages] => stdClass Object
(
[en-us] => 3
[pt-br] => 1
[ko-kr] => 1
)
[organisations] => stdClass Object
(
[Williams-Sonoma] => 1
[Verizon Wireless] => 1
[SK Telecom] => 1
[Oi Velox] => 1
[CenturyLink] => 1
)
[platforms] => stdClass Object
(
[iphone] => 2
[win8] => 1
[mac108] => 1
[ipad] => 1
)
)
stdClass Object
(
[mobilesafari] => 3
[safari] => 1
[chrome] => 1
)
stdClass Object
(
[Williams-Sonoma] => 1
[Verizon Wireless] => 1
[SK Telecom] => 1
[Oi Velox] => 1
[CenturyLink] => 1
)
3