PHP - JSON数组不能返回与name无关的值

时间:2016-07-01 10:27:31

标签: php arrays json

我有一个看起来像这样的json数组:

[{"name":"title_one","value":"something"},{"name":"title_two","value":"something 2"},{"name":"title_three","value":"something three"}]

我可以像这样得到数组和访问值:

$configarray = json_decode($configfile, true);


$valueone = $configarray[0]['value'];
$valuetwo = $configarray[1]['value'];
$valuethree = $configarray[2]['value'];

但是我会在这个json中的不同时间有不同的对(以及不同的顺序),所以我想通过获取它们的相关名称来访问这些值,我尝试了以下变体:

 $valueone = $configarray['title_one']['value'];
 $valuetwo = $configarray['title_two']['value'];
 $valuethree = $configarray['title_three']['value'];

但它失败并告诉我我有一个未定义的索引。如何通过对中的名称访问这些值?

2 个答案:

答案 0 :(得分:0)

$ configarray的输出是

阵 (     [0] => stdClass对象         (             [name] => title_one             [value] =>某物         )

[1] => stdClass Object
    (
        [name] => title_two
        [value] => something 2
    )

[2] => stdClass Object
    (
        [name] => title_three
        [value] => something three
    )

这就是为什么你不能通过

 $valueone = $configarray['title_one']['value'];
 $valuetwo = $configarray['title_two']['value'];
 $valuethree = $configarray['title_three']['value'];

使用foreach,您可以将值赋给新变量

foreach($config as $conf){
   echo $conf->value; echo "</br>";
}

答案 1 :(得分:0)

假设每个json对象中只有两个属性,你可以这样做:

$configfile  = '[{"name":"title_one","value":"something"},{"name":"title_two","value":"something 2"},{"name":"title_three","value":"something three"}]';
$configarray = json_decode($configfile, true);
$configarray = array_combine(array_column($configarray, 'name'), array_column($configarray, 'value'));

$valueone   = $configarray['title_one'];
$valuetwo   = $configarray['title_two'];
$valuethree = $configarray['title_three'];