Php 如何在一个数组中存储包含3个字段的多个注释?
上面只打印了一次注释数组,但不是针对$big_响应中的所有值Php 如何在一个数组中存储包含3个字段的多个注释?,php,arrays,json,Php,Arrays,Json,上面只打印了一次注释数组,但不是针对$big_响应中的所有值 foreach ($big_response as $data) { $comment_data[comment][name] = $data->name; $comment_data[comment][date] = $data->createdAt; $comment_data[comment][message] = $data->message; } 我正在尝试打印一个数组,
foreach ($big_response as $data) {
$comment_data[comment][name] = $data->name;
$comment_data[comment][date] = $data->createdAt;
$comment_data[comment][message] = $data->message;
}
我正在尝试打印一个数组,其结构如下:
array(2) { [0]=> array(0) { } ["comment"]=> array(3) { ["name"]=> NULL ["date"]=> string(19) "2013-01-07T08:56:23" ["message"]=> string(45) "HELLO WORLD" } }
所有值都是字符串类型。事实上,我想在json_编码后将结果数组存储在json文件中
我在哪里?请告诉我是否可以提供更多详细信息。问题在于,您基本上只是在每个循环中覆盖
$comment\u data[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
)
)
这个数组结果永远不会发生,因为您可以有多个键值相同的键comment
:
foreach ($big_response as $data) {
$comment_data[comment][name] = $data->name;
$comment_data[comment][date] = $data->createdAt;
$comment_data[comment][message] = $data->message;
}
在执行foreach
循环时,使用$big\u response
数组中的键
值尝试此操作:
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
)
)
其输出如下:
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
)
)
)
每次迭代都要替换数组元素。谢谢Jake,使用为我设计的密钥。仅出于学习目的,如果您能指导我找到一个资源,在那里我可以了解更多关于这个问题的信息,并自己创建复杂的数组结构,那将是非常棒的。谢谢@user2714639!但我的想法是,据我所知,没有任何资源可以解释数组每个值只能有一个唯一键这一基本概念。这只是我和其他人知道数组的行为方式。不仅在PHP中,而且在任何编程语言中。正确!我很笨。顺便说一句,我知道数组有一个值的唯一键,但还是会发生一些事情。谢谢Stefan。使用计数器而不是像杰克建议的那样使用big_response的钥匙是否有好处?性能有什么提高吗?我很好奇,因为你得到了更多的选票。不,你想怎么做就怎么做,试着找到一种风格,让你的代码更坚实,更少混乱。然后你会发现在你的个人情况下什么更有意义。但这需要一段时间,您获得的经验越多,您的代码就越可靠。
$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++;
}