简体   繁体   English

foreach 给我错误的结果

[英]foreach giving me wrong results

So, i have 2 multi dimensional arrays, i'm rendering both arrays through foreach loop and i have 3 condition's in nested foreach所以,我有 2 个多维 arrays,我正在通过 foreach 循环渲染 arrays,我在嵌套的 foreach 中有 3 个条件

1- when id match from both arrays then a new array assign to empty array 1-当来自两个 arrays 的 id 匹配时,然后将一个新数组分配给空数组

2- when id not match from array 1 with id array 2 then a new array assign to empty array 2-当数组 1 中的 id 与 id 数组 2 不匹配时,则将一个新数组分配给空数组

3- when id not match from array 2 with array 1 then do the same 3-当数组 2 中的 id 与数组 1 不匹配时,请执行相同操作

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我在数组 1 中有 19 个 arrays,在数组 2 中有相同的值,但它给了我 361 个结果作为回报,任何帮助将不胜感激

$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');                    
        }

    }
} 

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.此代码首先使用array_column()创建 2 个新的 arrays 由id索引,然后可以使用isset()在两个循环中使用它们,这比每次使用in_array快得多。

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...第一个循环检查 shopify 但不是数据库,第二个循环检查数据库但不是 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');
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM