我有两个数组,它们看起来都像
array(
array('key_id' => 1, 'value' => 4, 'whatever' => 'something'),
array('key_id' => 2, 'value' => 3, 'whatever' => 'something'),
array('key_id' => 3, 'value' => 2, 'whatever' => 'something'),
array('key_id' => 4, 'value' => 1, 'whatever' => 'something'),
);
他们会有一些相交key_id
的,会有一些出现在第一个数组中,但不是第二个,还有一些出现在第二个数组中但不是第一个。
我想获取第一个数组中所有 key_id 的数组,但不是第二个数组。例如
$a = array(
array('key_id' => 1, 'value' => 4, 'whatever' => 'something'),
array('key_id' => 2, 'value' => 3, 'whatever' => 'something'),
array('key_id' => 3, 'value' => 2, 'whatever' => 'something'),
);
$b = array(
array('key_id' => 3, 'value' => 2, 'whatever' => 'something'),
array('key_id' => 4, 'value' => 1, 'whatever' => 'something'),
);
我想要的输出是array(1,2);
我目前的方法是:
$keys = array('orig' => array(), 'new' => array());
array_map(function($array){
$keys['orig'][] = $array['key_id'];
}, $a);
array_map(function ($array) {
$keys['new'][] = $array['key_id'];
}, $b);
$difference = array_diff($keys['orig'], $keys['new']);
哪个应该起作用,但我想知道是否有更好的方法?
在下面使用eis的方法是我正在为问题提供上下文的工作示例:
<?php
$a = array(
array('key_id' => 1, 'value' => 4, 'whatever' => 'something'),
array('key_id' => 2, 'value' => 3, 'whatever' => 'something'),
array('key_id' => 3, 'value' => 'o', 'whatever' => 'something'),
array('key_id' => 5, 'value' => 'e', 'whatever' => 'something')
);
$b = array(
array('key_id' => 3, 'value' => 'n', 'whatever' => 'something'),
array('key_id' => 4, 'value' => 1, 'whatever' => 'something'),
array('key_id' => 5, 'value' => 'e', 'whatever' => 'something')
));
function compareKeyId($a, $b) {
if ($a['key_id'] === $b['key_id']) return 0;
return ($a['key_id'] > $b['key_id']) ? 1 : -1;
}
function compareKeyIdAndValue($a, $b) {
return ($a['key_id'] === $b['key_id'] && $a['value'] === $b['value']) ? 0 : -1;
}
$changed = array();
$removed = array_udiff($a, $b, 'compareKeyId');
$added = array_udiff($b, $a, 'compareKeyId');
//get the elements that are present in both arrays (remainder)
$r = array();
$r['new'] = array_udiff($b, $removed, $added, 'compareKeyId');
$r['old'] = array_udiff($a, $removed, $added, 'compareKeyId');
$changed = array();
$changed['old'] = array_udiff($r['old'], $r['new'], 'compareKeyIdAndValue');
$changed['new'] = array_udiff($r['new'], $r['old'], 'compareKeyIdAndValue');
die('<pre>'.print_r(array('removed' => $removed, 'added' => $added, 'changed' => $changed), true).'</pre>');
?>