Jump to content

Merging data from two multidimensional arrays


StevenTompkins
Go to solution Solved by Barand,

Recommended Posts

Hi wondering if there's a simple way to merge or update the data from one array to another . I've tried merge data but it just adds additional records rather than merging them off one common key.

 

The array is just simply adding a name to another array the format of both is as follows

 

Array 1

 

[0] => stdClass Object
(
[name] =>
[market] => Football
[selection] => 7051575

)

 

)

 

Array 2

 

Array
(
[0] => stdClass Object
(
[name] => Something
[market] =>
[selection] => 7051575

)

)

 

 

There are other fields but I'm just trying to merge the name from Array two into Array one using the selection as a common key. Is there an easy command like merge or do I have to loop thru the arrays to add the data.

 

Thanks

Link to comment
Share on other sites

I mentioned I've tried array_merge but it just adds the data as additional records into one new array. What code am I supposed to post as I'm looking for the code?

 

Here you go then array_merge($array1,$array2)

 

gives me

 

Array
(
[0] => stdClass Object

 

(
[name] => Something
[market] =>
[selection] => 7051575

)

 

[1] => stdClass Object

 

(
[name] =>
[market] => Football
[selection] => 7051575

 

)

 

 

 

 

rather than the array I'm hoping for

 

Array
(
[0] => stdClass Object

 

(
[name] => Something
[market] => Football
[selection] => 7051575

)

 

)

Edited by StevenTompkins
Link to comment
Share on other sites

Thanks, Barand I'll probably look into that method, the first array only needs to be scraped once to get the static data. I don't use php too often but find it very useful and quick for web scraping only later you start to realise it's limitations :(

 

I went with looping the array for now but if I get round to recoding I'll see if your suggestion works out better.

 

foreach((array)$array1 as $index ){
   
    foreach((array)$array2 as $value)
    {

if($index->selection==$value->selection){ $value->name=$index->name;break;}

}


}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.