0

I have two Object arrays. "ID" from array 1 corresponds to the same as "media_id" in array 2 I need to add the "album_ids" of array 2 to array 1.

Object 1;

Array ( [0] => stdClass Object ( [ID] => 2482 [post_author] => 6 [post_date] => 2014-07-31 07:59:26) [1] => stdClass Object ( [ID] => 2483 [post_author] => 6 [post_date] => 2014-07-31 07:59:28)

Object 2=

Array ( [0] => stdClass Object ( [album_id] => 52 [media_id] => 2482 ) [1] => stdClass Object ( [album_id] => 92 [media_id] => 2483 )

I need the end result to be:

Array ( [0] => stdClass Object ( [ID] => 2482 [post_author] => 6 [post_date] => 2014-07-31 07:59:26 [album_id] => 52) [1] => stdClass Object ( [ID] => 2483 [post_author] => 6 [post_date] => 2014-07-31 07:59:28 [album_id] => 92)

Thank you for the help!!

2
  • 1
    PHP works better with arrays rather than objects. You can cast 'stdClass' objects directly to arrays. You can then use the many 'array_*' functions. It will help to answer your question if you would reformat you 'data' so that it is easier to compare when reading it. Commented Jul 31, 2014 at 19:51
  • Thank you for the reply. I reformatted the code to help make things more clear. Commented Jul 31, 2014 at 20:07

1 Answer 1

1

As per your question, lets suppose you have two arrays of objects - array1 and array2.

aarry1 = Array( [0] => stdClass Object ( [ID] => 2482 [post_author] => 6 [post_date] => 2014-07-31 07:59:26) [1] => stdClass Object ( [ID] => 2483 [post_author] => 6 [post_date] => 2014-07-31 07:59:28)

array2= Array ( [0] => stdClass Object ( [album_id] => 52 [media_id] => 2482 ) [1] => stdClass Object ( [album_id] => 92 [media_id] => 2483 )

Now try out this code.

$albumids = array();
foreach ( $array2 as $key => $val) {
 $albumids[$val->media_id] = $val->album_id;
}

if(!empty($albumids)) {
 foreach ( $array1 as $key => $val) {
  if(isset($albumids[$val->ID])) {
    $val->album_id = $albumids[$val->ID];
  }
 }
}

print_r($array1);

You would get the expected result

Edit: I had to correct the following line from: $val->albumid = $albumids[$val->id]; to $val->album_id = $albumids[$val->ID];

2
  • This answer appears close but it's output makes all of the [album_id] => empty. Commented Jul 31, 2014 at 20:43
  • I made a slight typo change in your line: $val->albumid = $albumids[$val->id]; to read $val->album_id = $albumids[$val->ID]; and it works perfectly thank you! Commented Jul 31, 2014 at 20:54

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.