如何使用一个数组索引和另一个数组键值获取差异数组?

时间:2018-09-13 14:01:09

标签: php

我有多维数组:-

$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 

2 个答案:

答案 0 :(得分:1)

喜欢

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

诀窍是array_flip使用第二个数组并使用array_diff_key

Working example

$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))); 

答案 1 :(得分:0)

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

$diff = [];

foreach ($first as $key => $value) {
    if(!in_array($key, $second)) {
        $diff[$key] =  $value;
    }
}