如何将一个数组中的键与另一个数组中的值进行比较,并返回不匹配的结果? [重复]

问题描述 投票:0回答:3

我有多维数组:-

$first= array(
    [51581481] => array(
        'title' => 'Nike - L',
        'price' => '300.00',
        'vendor' => 'Vicky Fashion Point',
        'quantity' => -23,
    ),
    [45747894] => array(
        'title' => 'Honor Band A (Black) - Default Title',
        'price' => '2249.00',
        'vendor' => 'Honor',
        'quantity' => 8,
    )
);
$second = array(
    0 => '45747894',
    1 => '713776113',
);

我想比较两个数组并首先从数组中获取差异数据。我正在使用 array_diff 函数

$arr_diff= array_diff($first, $second);

此错误显示:-

ERROR: Array to string conversion 
php arrays filter key array-difference
3个回答
1
投票

就这样

$arr_diff  = array_diff_key($first, array_flip($second));

技巧是array_flip第二个数组并使用array_diff_key

工作示例

$first = array(
    51581481 => array(
        'title' => 'Nike - L',
        'price' => '300.00',
        'vendor' => 'Vicky Fashion Point',
        'quantity' => -23,
    ),
    45747894 => array(
        'title' => 'Honor Band A (Black) - Default Title',
        'price' => '2249.00',
        'vendor' => 'Honor',
        'quantity' => 8,
    ),
);
$second = array(
    0 => 45747894,
    1 => 713776113,
);


var_dump(array_diff_key($first, array_flip($second))); 

0
投票

您可以使用

array_search()
unset()
来区分两个数组。

$first= array( "51581481"=>array(
             'title' => 'Nike - L',
             'price' => '300.00',
             'vendor' => 'Vicky Fashion Point',
             'quantity' => -23,
            ),
        "45747894"=>array(
              'title' => 'Honor Band A (Black) - Default Title',
              'price' => '2249.00',
              'vendor' => 'Honor',
              'quantity' => 8,
            )
        );
$second=array("0" => '45747894',
             "1" => '713776113',
            );

$array_diff = [];
foreach($first as $key => $val)
{
    if(array_search($key, $second) !== false)
    {
        unset($first[$key]);//remove matched key record
    }
}

echo '<pre>';print_r($first);echo '</pre>';

预期输出:

Array
(
    [51581481] => Array
        (
            [title] => Nike - L
            [price] => 300.00
            [vendor] => Vicky Fashion Point
            [quantity] => -23
        )

)

0
投票

作为一个简单的解决方案,循环遍历第一个数组并检查第二个数组中是否存在该键以获得差异。

$diff = [];

foreach ($first as $key => $value) {
    if(!in_array($key, $second)) {
        $diff[$key] =  $value;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.