2013-04-05 128 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

相關問題