php,json到特定的字符串

时间:2015-07-03 02:32:46

标签: php arrays json

通过POST我得到这个JSON(可以有超过3个值)

{"preferences":["Theater","Opera","Danse"]}

好吧,我需要得到

array('Theater', 'Opera', 'Degustation')

json_decode不起作用。 你有什么想法吗? 提前谢谢

3 个答案:

答案 0 :(得分:0)

您可能已将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>';
?>

答案 1 :(得分:0)

JSON字符串包装在一个对象中(用花括号{}表示)。 json_decode将为您提供包装器对象,其“preferences”属性是您正在寻找的数组。

$wrapper = json_decode($json_string);
$array = $wrapper->preferences;
如果你使用的是旧版本的php,json_decode也可能无法使用。在这种情况下,你应该尝试一个php json库。

答案 2 :(得分:0)

尝试添加 true 参数:

$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"
}

这是你想要的。祝你好运!

相关问题