2013-11-25 43 views
0

我正在從Javascript接收一個JSON數組作爲$ _POST變量。如何逐行獲取PHP中的一級JSON值

我想獲取所有變量及其JSON值。我試圖像使用foreach一樣使用json_decode,但它不起作用。我的PHP代碼是

<?php 

$string = $_POST['json']; 
var_dump(json_decode($string, true)); 
foreach($string as $key => $value) { 
    echo $key . " : " . $value; 
} 

?> 

我的JSON是

[{"EXTAPP_ID":"9901","CATEGORY_ID":"10","LANGUAGE_CODE":"tr","CATEGORY_LANG_DESC":"TR AAA"},{"EXTAPP_ID":"9901","CATEGORY_ID":"10","LANGUAGE_CODE":"de","CATEGORY_LANG_DESC":"DE AAA"},{"EXTAPP_ID":"9901","CATEGORY_ID":"20","LANGUAGE_CODE":"de","CATEGORY_LANG_DESC":"DE XXX"},{"EXTAPP_ID":"9901","CATEGORY_ID":"20","LANGUAGE_CODE":"tr","CATEGORY_LANG_DESC":"TR YYY"},{"EXTAPP_ID":"9901","CATEGORY_ID":"10","LANGUAGE_CODE":"en","CATEGORY_LANG_DESC":"EN ZZZ"},{"EXTAPP_ID":"9901","CATEGORY_ID":"20","LANGUAGE_CODE":"en","CATEGORY_LANG_DESC":"EN VVV"}] 

返回像波紋管一陣列的要求(我沒貼的所有結果)

array(6) { 
    [0]=> 
    array(4) { 
    ["EXTAPP_ID"]=> 
    string(4) "9901" 
    ["CATEGORY_ID"]=> 
    string(2) "10" 
    ["LANGUAGE_CODE"]=> 
    string(2) "tr" 
    ["CATEGORY_LANG_DESC"]=> 
    string(19) "TR XXX" 
    } 
    [1]=> 
    array(4) { 
    ["EXTAPP_ID"]=> 
    string(4) "9901" 
    ["CATEGORY_ID"]=> 
    string(2) "10" 
    ["LANGUAGE_CODE"]=> 
    string(2) "de" 
    ["CATEGORY_LANG_DESC"]=> 
    string(17) "TR YYY" 
    } 
    [2]=> 

我所期待的是

EXTAPP_ID: 9901 
CATEGORY_ID:10 
LANGUAGE_CODE:de 
CATEGORY_LANG_DESC:DE AAA 
+0

得到期望的結果。必須要JSON第一解碼:'$ string = json_decode($ _ POST ['json'],true);' –

+0

你是什麼意思與「它沒有工作」?它輸出什麼錯誤? – Leonardo

+0

它返回狀陣列(6){ [0] => 陣列(4){ [ 「EXTAPP_ID」] => 串(4) 「9901」 [ 「CATEGORY_ID」] => 串的陣列( 2) 「10」 [ 「LANGUAGE_CODE」] => 串(2) 「TR」 [ 「CATEGORY_LANG_DESC」] => 串(19) 「TR XXX」 } [1] => 陣列(4 ){ [ 「EXTAPP_ID」] => 串(4) 「9901」 [ 「CATEGORY_ID」] => 串(2) 「10」 [ 「LANGUAGE_CODE」] => 串(2) 「的」 [ 「CATEGORY_LANG_DESC」] => string(17)「TR YYY」 } – Calipso

回答

1

解碼與$string = json_decode($_POST['json'], true);

字符串您可以通過下面的代碼

$string = $_POST['json']; 
$string = json_decode($string, true); 
foreach($string as $value) { 
    foreach($value as $k=>$v) { 
     echo $k . " : " . $v .'<br/>'; 
    } 
    echo '<hr>'; 
} 
+0

Catagory desc太長,我只是手動更改它。所以這不是問題 – Calipso

+0

請檢查我的更新答案 –

0

試試這個:

$string = json_decode($_POST['json'], true); 
foreach($string as $key => $value) { 
    echo $key . " : " . $value; 
} 
0

試試這個:

$string = $_POST['json']; 
$data = json_decode($string, true); 
var_dump($data); 
foreach($data as $key => $value) { 
    echo $key . " : " . $value; 
}