郵寄我得到這個JSON(中可以有超過3個值)PHP,JSON,以特定的字符串
{"preferences":["Theater","Opera","Danse"]}
嗯,我需要得到
array('Theater', 'Opera', 'Degustation')
json_decode不起作用。 你有什麼想法嗎? 預先感謝您
郵寄我得到這個JSON(中可以有超過3個值)PHP,JSON,以特定的字符串
{"preferences":["Theater","Opera","Danse"]}
嗯,我需要得到
array('Theater', 'Opera', 'Degustation')
json_decode不起作用。 你有什麼想法嗎? 預先感謝您
嘗試添加真正參數:
$jsonData = '{"preferences":["Theater","Opera","Danse"]}';
$arrayData = json_decode($jsonData, true);
var_dump($arrayData['preferences']);
最後一行輸出如下:
array(3) {
[0]=>
string(7) "Theater"
[1]=>
string(5) "Opera"
[2]=>
string(5) "Danse"
}
這是你想要的。祝你好運!
謝謝你的TRUE參數,正是我需要的:) – sim100
您可能已經使用json_decode()
函數的輸出作爲關聯數組,而您尚未告訴該函數爲您提供關聯數組,反之亦然!然而,以下將得到你陣列在preferences
指數:
<?php
$decoded = json_decode('{"preferences":["Theater","Opera","Danse"]}', true); // <-- note the second parameter is true.
echo '<pre>';
print_r($decoded['preferences']); // output: Array ([0] => Theater [1] => Opera [2] => Danse)
// ^^^^^^^^^^^^^^^^^^^^^^^
// Note the usage of the output of the function as an associated array :)
echo '</pre>';
?>
即JSON字符串被包裹在一個對象(由大括號表示爲{})。 json_decode會給你包裝對象的「preferences」屬性是你正在尋找的數組。
$wrapper = json_decode($json_string);
$array = $wrapper->preferences;
如果您使用的是舊版本的php,json_decode也可能不可用。在這種情況下,你應該嘗試一個php json庫。
你是什麼意思「json-decode不起作用」?當你嘗試時會發生什麼? – kittykittybangbang
我很確定它至少不會將第三個值更改爲另一個值,但除此之外也應該可以工作 –