PHP访问关联数组值

时间:2016-02-01 23:37:22

标签: php arrays json

我有一个键/值数组,如下所示:

Array (
  [a] => - Item 1.1 \n - Item 1.2 \n - Item 1.3
  [b] => - Item 2.1 \n Item 2.2 \n - Item 2.3 \n - Item 2.4
  [c] => - Item 3.1 \n - Item 3.2
)

我有另一个阵列,我试图设置等于第一个。基本上,我得到一个带有json编码数组的POST请求,然后我解码它,然后我尝试将一个数组的键/值设置为等于另一个数组的键/值。

这里有一些代码:

$requests = $this->get("request");
$notes_json = $requests->get("notes");
$notes = json_decode($notes_json, true);

$field_notes = array(
    "field_1" => $notes[a]
);

但它无法正常工作,我收到服务器(500)错误。然后我尝试echo $notes[g];,但我仍然得到(500)错误。任何人都可以告诉我为什么PHP不会让我只是访问数组键的特定值?

=====编辑=====

var_dump($notes)结果:

array(7) {
  ["a"]=>
  string(159) "- data 1.1
- data 1.2
- data 1.3
(note: extra data)
"
  ["b"]=>
  string(0) ""
  ["c"]=>
  string(25) "- data 3.1
"
  ["d"]=>
  string(24) "- data 4.1
"
  ["e"]=>
  string(16) "- data 5.1
"
  ["f"]=>
  string(34) "- data 6.1
"
  ["g"]=>
  string(18) "(note: extra data)
"
}

1 个答案:

答案 0 :(得分:0)

感谢我提问的评论者,解决方案很简单:在密钥周围加上引号

错误:echo $notes[g];

右:echo $notes['g'];

相关问题