2013-04-05 40 views
0

我有一个json数组wherer我想通过使用for循环来获取数字,然后将json拖到最后一个元素JSON数组的数组元素的,我在anarray超过3个对象,所以我很困惑如何解析JSON,直到最后一个元素, 我可以说你的想法如何解析json数组元素使用for循环来逐个获取值

Count($json); 
echo count; 
    for(i=0;i<l=count($json);i++) 
{ 
then print the value of each key 
} 

我坚持,因为有没有固定长度的JSON我得到,因为它是一个服务器的响应它可能会返回一个对象可能是两次或三次或许多,所以我认为这将是更好的循环做,因为JSON包含超过一个带3个键的json,比如国家可以有更多不止一个状态,一个国家可以有一个以上的地区,plaese帮助我,我坚持了最后2天的问题 谢谢

+0

您可以在参数做一个PHP函数与JSON数组,并调用该函数,如果电流值'is_array',打印别的! – JoDev 2013-04-05 09:29:44

回答

1

一个想法:

function printJson($json) { 
     foreach($json as $index=>$value) { 
      if(is_array($value)) { 
       printJson($value); 
      } else { 
       echo 'Value :'.$value.'<br />'; 
      } 
     } 

} 
$stringJson = "{'location':[{...}]}"; //for example 
printJson(json_decode($stringJson)); 
+0

如何调用此函数 – Sree 2013-04-05 09:36:34

+0

我的json是[{“location”:[{“building”:[“Default Building”],“name”:“Default Location”}],“name”:“Default Organization”}, {“location”:[{“building”:[“test_loc1_building1”,“test_loc1_building2”],“name”:“test location1”},{“building”:[“test_loc2_building2”],“name”:“test location2” }],“name”:“test Organization”}] – Sree 2013-04-05 09:37:17

0

您也可以解码JSON使用json_decode()这将给你的PHP变量,你可以很容易地使用PHP迭代。

例如。

$string = '{"image":"fox.png","puzzlepieces":{"f":{"puzzlepiece":"one","position":"top:121px;left:389px;"},"x":{"puzzlepiece":"three","position":"top:164px;left:455px;"},"o":{"puzzlepiece":"two","position":"top:52px;left:435px;"}}}'; 

var_dump(json_decode($string)); 

将输出作为

object(stdClass)[1] 
    public 'image' => string 'fox.png' (length=7) 
    public 'puzzlepieces' => 
    object(stdClass)[2] 
     public 'f' => 
     object(stdClass)[3] 
      public 'puzzlepiece' => string 'one' (length=3) 
      public 'position' => string 'top:121px;left:389px;' (length=21) 
     public 'x' => 
     object(stdClass)[4] 
      public 'puzzlepiece' => string 'three' (length=5) 
      public 'position' => string 'top:164px;left:455px;' (length=21) 
     public 'o' => 
     object(stdClass)[5] 
      public 'puzzlepiece' => string 'two' (length=3) 
      public 'position' => string 'top:52px;left:435px;' (length=20) 

我Xdebug扩展是在WAMP让你的var_dump可能会有点不同格式但总体来说,你会得到从u能重复使用数组PHP变量foreach或其他循环。

了解更多关于json_decode here

相关问题