Wednesday, 15 September 2010

Json fetching child elements using php -



Json fetching child elements using php -

i .net background , not asking code need suggestion can pull kid nodes. json

{ "state of origin 2014":{ "1471137":{ "eventid":1471137, "parenteventid":1471074, "mainevent":"state of origin series 2014", "outcomedatetime":"2014-06-18 20:10:00.0000000", "competition":"state of origin 2014", "competitors":{ "activecompetitors":3, "competitors":[ { "team":"new south wales (2 - 1)", "win":"2.15" }, { "team":"new south wales (3 - 0)", "win":"3.05" }, { "team":"queensland (2 - 1)", "win":"3.30" } ], "totalcompetitors":3, "haswinodds":true }, "eventstatus":"open", "issuspended":false, "allowbets":true }, "1471074":{ "eventid":1471074, "parenteventid":0, "mainevent":"state of origin series 2014", "outcomedatetime":"2014-07-09 20:10:00.0000000", "competition":"state of origin 2014", "competitors":{ "activecompetitors":2, "competitors":[ { "team":"new south wales", "win":"1.33" }, { "team":"queensland", "win":"3.30" } ], "totalcompetitors":2, "haswinodds":true }, "eventstatus":"open", "issuspended":false, "allowbets":true } }, "state of origin 2014 game 2":{ "3608662":{ "eventid":3608662, "parenteventid":3269132, "mainevent":"new south wales v queensland", "competitors":{ "activecompetitors":39, "competitors":[ { "teamname":"new south wales 6-10", "win":"4.70" }, { "teamname":"queensland 91+", "win":"201.00" } ], "totalcompetitors":39, "haswinodds":true }, "eventstatus":"open", "issuspended":false, "allowbets":true } } }

this have done. able root element , want go 2 levels downwards grap eventid , outcomedatetime.

php code

$json_a=json_decode($string,true); foreach ($json_a $root_element => $childnode) { echo($childnode['eventid']); echo($childnode['outcomedatetime']); echo "<br>"; }

if can give me way 2 levels downwards can work on other scripts. had posted question before not welcomed responses may not able express question in improve way , many thought asking total source code. time need method grap kid elements. thanks

try this

$json_a=json_decode($string,true); foreach ($json_a $root_element => $childnode) { foreach( $childnode $ckey => $subchild) { echo $subchild['eventid']; echo $subchild['outcomedatetime']; // check whether competitors array , array count > 0 if (is_array($subchild['competitors']['competitors']) , count ($subchild['competitors']['competitors']) > 0 ) { foreach($subchild['competitors']['competitors'] $compkey => $compval) { // since array contains team , teamname , utilize array_key_exists check whick key utilize $teamname = array_key_exists('team',$compval) ? $compval['team'] : $compval['teamname']; $win = $compval['win']; echo $teamname; echo $win; } } } }

you have nested foreach accomplish desired output

also since echo language build , not function not mandatory utilize ( ) braces in echo statement

php json cakephp-2.0

No comments:

Post a Comment