I have two arrays.
$primary = array(
[0] => array(
'name' => 'PPT Shop',
'place_id' => '1000',
'category' => '220,221',
'address' =>
),
[1] => array(
'name' => 'Meat Shop',
'place_id' => '1001',
'category' => '220,221'
'address' =>
),
[2] => array(
'name' => 'Bikini Shop',
'place_id' => '1010',
'category' => '100,102'
'address' =>
),
[3] => array(
'name' => 'Knife Shop',
'place_id' => '1012',
'category' => '1,3'
'address' =>
)
)
$moredata = array(
[0] => array(
'id' => '1000',
'category' => '900,901'
'address' => '35 Lawrence Park',
'phone' => '9000000099'
),
[1] => array(
'id' => '1001',
'category' => '909,300'
'address' => '39 Park Avenue',
),
[2] => array(
'id' => '1010',
'category' => '50,45'
'address' => '35 Trump Park',
'phone' => '8900000099'
)
)
I want to compare each data of $moredata with each data of $primary, and check if the place_id
from $primary exists in $moredata. If it matches, then the corresponding records of that particular key will be updated. For example,
$newPrimary = array(
[0] => array(
'name' => 'PPT Shop',
'place_id' => '1000',
'category' => '220,221,900,901',
'address' => '35 Lawrence Park',
'phone' => '9000000099'
),
[1] => array(
'name' => 'Meat Shop',
'place_id' => '220,221,1001',
'category' => '220,221,909,300',
'address' => '39 Park Avenue',
),
[2] => array(
'name' => 'Bikini Shop',
'place_id' => '1010',
'category' => '100,102,50,45'
'address' => '35 Trump Park',
'phone' => '8900000099'
),
[3] => array(
'name' => 'Knife Shop',
'place_id' => '1012',
'category' => '1,3'
'address' =>
)
)
place_id(1000) of primary matches with id(1000) of moredata, so the place_id(1000) of newPrimary is like this:-
array(
'name' => 'PPT Shop',
'place_id' => '1000',
'category' => '220,221,900,901', // the categories get concated
'address' => '35 Lawrence Park',
'phone' => '9000000099'
)
However, for place_id(1001) of primary doesn't have phone field, so the id(1001) of newPrimary is like this:-
array(
'name' => 'Meat Shop',
'place_id' => '1001',
'category' => '220,221,909,300',
'address' => '39 Park Avenue',
)
place_id(1012) has no match, so it remains unchanged.
How can I create an array similar to newPrimary? It would be better if we can append the fields from moredata to the corresponding record from primary. I achieved the same using double foreach loop. I want to achieve this is a way to have lesser execution time.
foreach($primary as $key_fs => $prm)
{
foreach($moredata as $key_place => $pc)
{
if($prm['place_id'] == $pc['id'])
{
if(isset($pc['address']) && !empty($pc['address']))
$primary[$key_fs]['address'] = $pc['address'];
if(isset($pc['phone']) && !empty($pc['phone']))
$primary[$key_fs]['phone'] = $pc['phone'];
if(isset($pc['category']) && !empty($pc['category']))
$primary[$key_fs]['category'] .= ','.$pc['category'];
break;
}
}
}
Note:- The two arrays will have same dimension, but may not have same order.