如何在数组中存储3个字段的多个注释?

时间:2013-12-28 20:05:27

标签: php arrays json

 foreach ($big_response as $data) {
     $comment_data[comment][name] = $data->name;
     $comment_data[comment][date] = $data->createdAt;
     $comment_data[comment][message] = $data->message;
 }

上面只打印了一个注释数组,但不是$ big_response中的所有值。

 array(2) { [0]=> array(0) { } ["comment"]=> array(3) { ["name"]=> NULL ["date"]=> string(19) "2013-01-07T08:56:23" ["message"]=> string(45) "HELLO WORLD" } } 

我正在尝试打印如下结构的数组:

    Array
    (
    [comment] => Array
      (
      [name] => Tom
      [date] => 12/12/12
      [message] => Hello World
      )
    [comment] => Array
      (
      [name] => Andy
      [date] => 12/12/14
      [message] => Hello World2
      )
    [comment] => Array
      (
      [name] => Peter
      [date] => 12/12/13
      [message] => Hello World3
      )
    )

所有值都是字符串类型。实际上我想在json_encode(ing)之后将结果数组存储在json文件中。

我缺少哪里?让我知道如果我能提供更多细节。

2 个答案:

答案 0 :(得分:2)

添加一个计数器:

$i = 0;
foreach ($big_response as $data) {
   $comment_data[comment][$i][name] = $data->name;
   $comment_data[comment][$i][date] = $data->createdAt;
   $comment_data[comment][$i][message] = $data->message;
   $i++;
}

答案 1 :(得分:1)

这个问题是你基本上只是用每个循环覆盖$comment_data[comment]…

foreach ($big_response as $data) {
  $comment_data[comment][name] = $data->name;
  $comment_data[comment][date] = $data->createdAt;
  $comment_data[comment][message] = $data->message;
}

此数组结果永远不会发生,因为您可以使用具有相同键值comment的多个键:

Array
(
[comment] => Array
  (
  [name] => Tom
  [date] => 12/12/12
  [message] => Hello World
  )
[comment] => Array
  (
  [name] => Andy
  [date] => 12/12/14
  [message] => Hello World2
  )
[comment] => Array
  (
  [name] => Peter
  [date] => 12/12/13
  [message] => Hello World3
  )
)

在执行key循环时,尝试使用$big_response数组中的foreach值:

foreach ($big_response as $data_key => $data_value) {
  $comment_data[$data_key][comment][name] = $data->name;
  $comment_data[$data_key][comment][date] = $data->createdAt;
  $comment_data[$data_key][comment][message] = $data->message;
}

这个的输出是这样的:

Array (
  [0] => Array (
    [comment] => Array (
      [name] => Tom
      [date] => 12/12/12
      [message] => Hello World
    )
  )
  [1] => Array (
    [comment] => Array (
      [name] => Andy
      [date] => 12/12/14
      [message] => Hello World2
    )
  )
  [2] => Array (
    [comment] => Array (
      [name] => Peter
      [date] => 12/12/13
      [message] => Hello World3
    )
  )
)