php中多维数组和一维数组的比较


Comparing Multi and single dimensional arrays in php

我是php的新手,只是在玩一些数组。我想从不同维度的数组中获得以下内容

以下是多维阵列

$a = array(
array(
    'productsid' => 90,
    'CouponID' => 50
),
array(
    'productsid' => 80,
    'CouponID' => 95
),
  array(
    'productsid' => 80,
    'CouponID' => 95
));

以下是一维阵列:

$b = array(80,90,95);

我只想将数组的productsid索引与一维数组进行比较,并想获取与其相等的数据。

我已经尝试过以下循环来打印,但它只给出productsid的值,但我想要完整的数组。但只能通过将Productid与第二个数组进行比较。

for ($i = 0; $i < 3; $i++) {
foreach ($a[$i] as $key => $value) {
    foreach ($b as $c) {
        if ($value == $c) {
            echo $value .'<br>';
        }
    }
} }

看起来您正在寻找in_array():

$result = array();
foreach($a as $item)
    if(in_array($item['productsid'], $b))
        $result []= $item;

或者,以一种更简洁(但可读性较差的IMO)的方式:

$result = array_filter($a, function($item) use($b) {
    return in_array($item['productsid'], $b);
});

对于您的测试数据来说,这并不重要,但如果您的数组很大和/或此循环将运行多次,您可以通过将查找数组转换为哈希表并使用O(1)密钥查找而不是线性数组搜索来获得更好的性能:

$bs = array_flip($b);
$result = array_filter($a, function($item) use($bs) {
    return isset($bs[$item['productsid']]);
});
$b = array(80,90,95);
$c = array();
foreach($a as $val) {
    if(in_array($val['productsid'],$b)) {
        $c[] = $val;    
    }
}
echo "<pre>";
print_r($c);

试试这个:

foreach($a as $ar) {
    if (in_array($ar['productsid'], $b))
        print_r($ar);
}