简体   繁体   中英

Adding new keys & values to Associative array in PHP?

I'm building a web scraper to check prices... so I have 2 arrays and I'm trying to merge the data into one array. First array is called $results and is like so:

Array ( 
[0] => Array ( 
[id] => 0 
    [myTitle] => Product One text... 
    [myImage] => Some url...
    [myPrice] => My price
) 

[1] => Array ( 
[id] => 1 
    [myTitle] => Product Two text... 
    [myImage] => Some url...
    [myPrice] => My price
 ) 
) 

And a second array called imaginatively: $results2:

Array ( 
[0] => Array ( 
    [amzId] => 0 
    [amzTitle] => Amazon Product One text... 
    [amzPrice] => Amazon price
) 

[1] => Array ( 
    [amzId] => 1
    [amzTitle] => Amazon Product Two text...
    [amzPrice] => Amazon price
 )  
)

I need to add the second arrays keys and values to the first, where the Id and 'amzId' are the same.

Array ( 
[0] => Array ( 
[id] => 0 
    [myTitle] => Product One text... 
    [myImage] => Some url...
    [myPrice] => My price
    [amzId] => 0 
    [amzTitle] => Amazon Product One text... 
    [amzPrice] => Amazon price
) 

[1] => Array ( 
[id] => 1 
    [myTitle] => Product Two text... 
    [myImage] => Some url...
    [myPrice] => My price
    [amzId] => 1 
    [amzTitle] => Amazon Product Two text... 
    [amzPrice] => Amazon price
 ) 
)

I can't figure out how to best do this. Or if I'd be better off adding the new keys and values to original $results array at the foreach loop when I'm getting the data (for the $results2 array), so I wouldn't need a second array?

Any help would be greatly appreciated!

Try to use this function . .

$arr3 = array_merge($arr1,$arr2);

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