简体   繁体   中英

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM