在 Foreach 数组中插入 If Else PHP

Insert in If Else in Foreach Array PHP

问题:当 $Current 与所有 $sub 不匹配时插入 $Current。

foreach ($array1 as $index=>$Current){
        foreach ($array2 as $key=>$subs){
            echo "\nCurrent: ".$Current; //get current 
            echo "\nsubs: ".$subs; //get subs
            if ($Current== $subs){
                echo "\n++++++\n";
            } else{
                echo "\n=====\n";
                $sql = "INSERT INTO `#__table` (user_id, cat_id, subs) VALUES (".$userid.",".$other_array [$index].",".$Current.")";
                echo "\n".$sql;
            }
        }

    }

实际输出为:

Current: 1
subs: 9
=====

INSERT INTO `#__table` (user_id, cat_id, subs) VALUES (1,1,1)
Current: 1
subs: 11
=====

INSERT INTO `#__table` (user_id, cat_id, subs) VALUES (1,1,1)
Current: 1
Subs: 1
+++++

我的预期输出应该是在比较当前和子程序不同后执行 Insert sql。这可能是这样的:

Current: 1
subs: 9
=====

Current: 1
subs: 11
=====

Current: 1
Subs: 1
+++++

// EXECUTE THIS AFTER COMPARING ALL Current and subs *** 
INSERT INTO `#__table` (user_id, cat_id, subs) VALUES (1,1,Current)

那么foreach循环应该怎么写呢?还是我不应该使用 foreach?

请帮忙。谢谢。

如果我没理解错的话,你想遍历$Current,如果$Current不存在于$subs中,你想把它插入到数据库中。

尝试使用 in_array 函数,如下所示:

foreach ($array1 as $index=>$Current){
    if (!in_array($Current, $array2))
        echo "\n=====\n";
        $sql = "INSERT INTO `#__table` (user_id, cat_id, subs) VALUES (".$userid.",".$other_array [$index].",".$Current.")";
        echo "\n".$sql;
    }
}