我在尝试找到最好的方法时遇到了麻烦,我的代码:
$purch = DB::getInstance()->select("SELECT * FROM `purchased`");
foreach($a as $val) {
foreach($purch as $v) {
$v['purchased_sape_ref_id']; // CONTAINS THE ID FROM THE DB //
$val; // CONTAINS THE ID IN THE ARRAY //
if (in_array($v, $val)) {
echo "This id is in the $a array: " . $v['purchased_sape_ref_id'];
} else {
echo "This id is not in the $a array: " . $v['purchased_sape_ref_id'];
}
}
}
变量$a
是一个数组,我已经用ID(总共90个)提交了它。使用$v
的mysql查询包含87个值,因此数组$a
包含的值比$v
多3个(从数据库中提取)
如何显示3个附加值?
答案 0 :(得分:1)
您可以使用array_diff
尝试以下解决方案:
$diff = array_diff($a, array_column($purch, 'purchased_sape_ref_id'));
现在,您可以输出$a
:)中存在的$a
中的所有值,并且可以输出$diff
中$a
中不存在的所有值。
array_diff
为您提供第一个数组中不在第二个数组上的所有值(作为数组)。使用array_column
,您可以直接访问数组的列。因此,您可以在列$purch
上获得包含purchased_sape_ref_id
所有值的数组。
<?php
$a = [1, 2, 3, 4, 5];
$purch = [
['test_col' => 'hello', 'purchased_sape_ref_id' => 1],
['test_col' => 'world', 'purchased_sape_ref_id' => 2],
['test_col' => 'stack', 'purchased_sape_ref_id' => 3]
];
$diff = array_diff($a, array_column($purch, 'purchased_sape_ref_id'));
foreach ($a as $a_value) {
if (!in_array($a_value, $diff)) {
echo 'This id is in the $a array: '.$a_value."\n";
} else {
echo 'This id is not in the $a array: '.$a_value."\n";
}
}