简体   繁体   中英

Adding to multidimensional arrays PHP

In my function im storing in $var1 a query from the database of posts. And im storing in $var2 a query from the database of images from the posts. (Each has a key post_id to connect them.)

$var1 will return something like this.

array (
  [0] => stdClass Object
     (
         [post_id] => 210
         [post_title] => title
     )
  [1] => stdClass Object
     (
         [post_id] => 212
         [post_title] => title
     )
)

and $var2 will return something like this.

array (
  [0] => stdClass Object
     (
         [post_id] => 210
         [post_meta_key] => image
         [post_meta_value] => image_value
     )
  [1] => stdClass Object
     (
         [post_id] => 212
         [post_meta_key] => flag
         [post_meta_value] => flag_value
     )
  [2] => stdClass Object
     (
         [post_id] => 210
         [post_meta_key] => image
         [post_meta_value] => image_value
     )
  [3] => stdClass Object
     (
         [post_id] => 102
         [post_meta_key] => image
         [post_meta_value] => image_value
     )
)

I would like to create a foreach from $var1 and if $var1[post_id] = $var2[post_id] than $var1 will be edited to something like this

array (
  [0] => stdClass Object
     (
         [post_id] => 210
         [post_title] => title
         [image] => stdClass Object
             (
                 [0] => image_value
                 [1] => image_value
             )
     )
  [1] => stdClass Object
     (
         [post_id] => 212
         [post_title] => title
     )
)

How can i do this?

foreach ($var1 as &$post1)
{
  foreach($var2 as $post2)
  {
    if ($post1->post_id == $post2->post_id)
    {
       $post1->image = (object)array(
         $post2->post_meta_value
       );
    }
  }
}

Better use arrays instead of objects here:

foreach ($var2 as $key2=>$var2){
    if (!empty($var1[$key2])){
        $var1[$key2]['image']->$var2;
    }
}

You could cast arrays and objects back and forth with

$array = (array)$object;
$object = (object)$array;

This is what you want:

foreach ( $var1 as $v1 )
{
    foreach ( $var2 as $v2 )
    {
        if ( $v1['post_id'] == $v2['post_id'] )
            $v1['image'][] = $v2['post_meta_value'];
    }
}

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