Array包含的值多于db

时间:2017-08-02 16:55:01

标签: php

我在尝试找到最好的方法时遇到了麻烦,我的代码:

$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个附加值?

1 个答案:

答案 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所有值的数组。

演示(http://ideone.com/2azqOd):

<?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";
    }
}