开发者

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

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() treats array as a stack, and pushes the passed variables onto the end of array.

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. Also see:

  • http://www.php.net/manual/en/language.types.array.php


I agree with others. Besides, as php manual note:

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.

http://php.net/manual/en/function.array-push.php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜