2014-09-03 35 views
-2

在JSON數組鍵的值如何獲得密鑰關聯獲取在PHP

[{"name":"challenge","properties":[{"name":"mobileNo","value":"aa"},{"name":"challengeT","value":"1Day"},{"name":"emailId","value":"[email protected]"},{"name":"deviceId","value":"9500e297-081b-4f97-93b7-dafddc55db31"}]},{"name":"challenge","properties":[{"name":"emailId","value":"[email protected]"},{"name":"mobileNo","value":"345345"},{"name":"deviceId","value":"435435dfgdfg"}]}] 
+0

1.你的json無效; 2.數據驗證完成後'json_decode',然後發出'var_dump'來檢查相應的PHP結構。 – moonwave99 2014-09-03 09:46:04

+0

'如何獲取關鍵相關的對應值?這是一個什麼樣的問題?你試圖得到什麼樣的最終結果? – Ghost 2014-09-03 10:33:18

回答

1

您的JSON對應的值是有效的。您可以在以下網址驗證 網站:http://jsonlint.com/

您必須使用php「json_decode()」函數來解碼json編碼的數據。 基本上json_decode()函數將JSON數據轉換爲PHP數組。

語法:json_decode(數據,dataTypeBoolean,深度,選項)

數據: - 要在PHP解碼JSON數據。

dataTypeBoolean(可選): - 布爾值,使函數返回一個PHP關聯數組,如果設置爲「真」,或者如果省略該參數返回一個PHP stdClass的對象或將其設置爲「假」。這兩種數據類型都可以像數組一樣訪問,並使用基於數組的PHP循環進行分析。

深度: - 可選遞歸限制。使用整數作爲此參數的值。

選項: - 可選的JSON_BIGINT_AS_STRING參數。

現在來到你的代碼

$json_string = '[{"name":"challenge","properties":[{"name":"mobileNo","value":"aa"},{"name":"challengeT","value":"1Day"},{"name":"emailId","value":"[email protected]"},{"name":"deviceId","value":"9500e297-081b-4f97-93b7-dafddc55db31"}]},{"name":"challenge","properties":[{"name":"emailId","value":"[email protected]"},{"name":"mobileNo","value":"345345"},{"name":"deviceId","value":"435435dfgdfg"}]}]' ; 

指定一個有效的JSON數據中單QUOT的( '')作爲 JSON字符串已經有雙quots一個變量$ json_string。

// here i am decoding a json string by using a php 'json_decode' function, as mentioned above & passing a true parameter to get a PHP associative array otherwise it will bydefault return a PHP std class objecy array. 

$json_decoded_data = json_decode($json_string, true); 

// just can check here your encoded array data. 
// echo '<pre>'; 
// print_r($json_decoded_data); 

// loop to extract data from an array 
foreach ($json_decoded_data as $key => $value) { 
    echo "$key <br/>"; 
    foreach ($value as $key2 => $value2) { 
     echo "$key2 = $value2 <br />"; 
    } 
} 

Output : 
0 
name = challenge 
properties = Array 
1 
name = challenge 
properties = Array 
+0

希望這會幫助你... :) – Aksh 2014-09-03 17:46:55