0

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?

2
  • Cant you modify your query to return all the relevant data? Commented Aug 9, 2011 at 11:33
  • I cant because the second query can have different post_meta_key for the same post_ids. Such as post_id = 200 can have post_meta_key' = flag AND post_meta_key` = image... Commented Aug 9, 2011 at 11:37

3 Answers 3

1
foreach ($var1 as &$post1)
{
  foreach($var2 as $post2)
  {
    if ($post1->post_id == $post2->post_id)
    {
       $post1->image = (object)array(
         $post2->post_meta_value
       );
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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;

Comments

0

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'];
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.