2013-11-28 55 views
0

我把JSON對象發送到服務器。在服務器端,我必須用PHP解析這個obj。用PHP解析JSON - 最有效的方法

我被困在循環中。我不知道如何進行循環。

我正在尋找最有效的方法來解析這個對象並將所有變量保存到數據庫中。

[ 
{"ADI":{"id":-1,"danger":0}}, 
{"ADI":{"id":3,"danger":0}}, 
{"ADI":{"id":3,"danger":0}}, 
{"ALE":{"_id":1,"_name":"Milk","contain":false}}, 
{"ALE":{"_id":2,"_name":"cfg","contain":false}}, 
{"ALE":{"_id":4,"_name":"Lakt","contain":false}}, 
{"PRO":{"image":"","code":"123456","name":"jfbj"}}, 
{"USER":{"email":"[email protected]"}} 
] 

現在我已經做到了這一點:

$string = file_get_contents('php://input'); 

$array = json_decode($string, true); 
//print_r($array); 

foreach ($array as $t => $index) { 
    foreach ($index as $vas => $r) { 
    //Here I'm stuck!!! 
    } 
} 
+1

您是否正在尋找一種替代到'json_decode()'?爲什麼? –

+0

似乎你要走對了......你面對什麼確切的問題? – Rikesh

+0

你究竟想要達到什麼樣的目標?你卡在哪裏? –

回答

1

你可以從JSON搶值

<?php 
$string = '[ 
{"ADI":{"id":-1,"danger":0}}, 
{"ADI":{"id":3,"danger":0}}, 
{"ADI":{"id":3,"danger":0}}, 
{"ALE":{"_id":1,"_name":"Milk","contain":false}}, 
{"ALE":{"_id":2,"_name":"cfg","contain":false}}, 
{"ALE":{"_id":4,"_name":"Lakt","contain":false}}, 
{"PRO":{"image":"","code":"123456","name":"jfbj"}}, 
{"USER":{"email":"[email protected]"}} 
]'; 
$array = json_decode($string, true); 
echo "<pre>"; 
//print_r($array);exit; 
for ($i=0;$i<=(count($array)-1);$i++){ 
    //print_r($array[$i]); 
    if (array_key_exists("ADI",$array[$i])) { 
     $ArrVal = $array[$i]['ADI']; 
     $id = $ArrVal['id']; 
     $danger = $ArrVal['danger']; 
     echo "$id,$danger "; 
    } 
} 
?> 
1

檢查了這一點:

echo "<pre>"; 
print_r($array); 

for ($i=0; $i < count($array); $i++) { 
    if(isset($array[$i]["ADI"])){ 
    print_r($array[$i]["ADI"]); 
    } 

    if(isset($array[$i]["ALE"])){ 
    print_r($array[$i]["ALE"]); 
    } 
} 
echo "</pre>";