Reputation: 11
So, i have 2 multi dimensional arrays, i'm rendering both arrays through foreach loop and i have 3 condition's in nested foreach
1- when id match from both arrays then a new array assign to empty array
2- when id not match from array 1 with id array 2 then a new array assign to empty array
3- when id not match from array 2 with array 1 then do the same
i have 19 arrays in array 1 and same in array 2 but it giving me 361 results in return any help will be appreciated
$allProducts = array();
foreach ($shopifyProducts as $row)
{
foreach ($db_Products as $subRow)
{
if ($row['id'] == $subRow['product_id'])
{
$allProducts[] = array('id' => $row['id'], 'status' => 'db+shopify');
}
else if ($row['id'] != $subRow['product_id'])
{
$allProducts[] = array('id' => $row['id'] ,'status' => 'not exist in db');
}
else if ($subRow['product_id'] != $row['id'])
{
$allProducts = array('id' => $subRow['product_id'] , 'status' => 'not exist at shopify');
}
}
}
Upvotes: 1
Views: 86
Reputation: 57121
This code first creates 2 new arrays indexed by the id
using array_column()
, these can then be used in two loops using isset()
which is a lot quicker than using in_array
each time.
The first loop checks for in both and in shopify but not the database, the second loop checks for in the database but not shopify...
$newArray1 = array_column($array1, null, "id");
$newArray2 = array_column($array2, null, "id");
$allProducts = array();
foreach ( $array1 as $row ) {
if ( isset ( $newArray2[$row['id']]) ) {
$allProducts[] = array('id' => $row['id'], 'status' => 'db+shopify');
}
else {
$allProducts[] = array('id' => $row['id'] ,'status' => 'not exist in db');
}
}
foreach ( $array2 as $row ) {
if ( !isset ( $newArray1[$row['id']]) ) {
$allProducts[] = array('id' => $row['id'] ,'status' => 'not exist at shopify');
}
}
Upvotes: 1