[英]PHP array_push with key => value
Here is my code这是我的代码
foreach ($query1 as $post)
{
foreach ($query2 as $data)
{
if ($post->post_id == $data->post_id)
{
// add all actions from a post to its array
if (!isset($post->post_meta))
{
$post->post_meta = array( strtolower($data->post_meta_key) => $data->post_meta_value );
}
else
{
array_push( $post->post_meta[strtolower($data->post_meta_key)] = $data->post_meta_value );
}
}
}
}
Im not sure how to fix the code.我不确定如何修复代码。 Im not getting the value, only the key, and a few errors.我没有得到价值,只有钥匙和一些错误。
array_push() expects at least 2 parameters, 1 given array_push() 至少需要 2 个参数,1 个给定
It should print out something like this它应该打印出这样的东西
[0] => stdClass Object
(
[post_id] => 218
[post_meta] => Array
(
[flagged] => 0
[deleted] => 1
)
)
Do you mean this?你是这个意思吗?
$post->post_meta[strtolower($data->post_meta_key)] = $data->post_meta_value;
i think, you need this:我想,你需要这个:
$post->post_meta[strtolower($data->post_meta_key)] = $data->post_meta_value;
From the manual page of array_push
(emphasis mine):从array_push
的手册页(强调我的):
array_push()
treats array as a stack , and pushes the passed variables onto the end of array.array_push()
将数组视为堆栈,并将传递的变量推送到数组的末尾。
So you cannot pass a key.所以你不能传递密钥。 If you want to pass a key, use如果要传递密钥,请使用
$yourArray[$theKey] = $theValue;
which will then either overwrite the $theValue
for $theKey
if it already exists or append it to the end of the array.然后,如果$theKey
theKey 已经存在,它将覆盖$theValue
,或者将 append 覆盖到数组的末尾。 Also see:另见:
I agree with others.我同意其他人的观点。 Besides, as php manual note:此外,作为 php 手册注意:
Note: If you use array_push()
to add one element to the array it's better to use $array[] =
because in that way there is no overhead of calling a function.注意:如果您使用array_push()
向数组添加一个元素,最好使用$array[] =
因为这样就没有调用 function 的开销。
http://php.net/manual/en/function.array-push.php http://php.net/manual/en/function.array-push.php
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.