Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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!!

share|improve this question
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. –  Ryan Vincent 16 hours ago
    
Thank you for the reply. I reformatted the code to help make things more clear. –  mithrix 16 hours ago

1 Answer 1

up vote 1 down vote accepted

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

share|improve this answer
    
This answer appears close but it's output makes all of the [album_id] => empty. –  mithrix 15 hours ago
    
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! –  mithrix 15 hours ago
    
@mithrix- thanks. that was some typo mistake :) –  Suraj Kumar 6 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.