我有两个这样的多维数组:
$original = Array (
[0] => Array
(
[time] => 1364690340
[memberid] => 90
[type] => single
)
[1] => Array
(
[time] => 1364690341
[memberid] => 92
[type] => fixed
)
[2] => Array
(
[time] => 1364690342
[memberid] => 96
[type] => single
)
)
和第二个像这样
$new = Array (
[0] => Array
(
[time] => 1364825750
[memberid] => 90
[type] => single
)
[1] => Array
(
[time] => 1364825751
[memberid] => 92
[type] => single
)
[2] => Array
(
[time] => 1364825752
[memberid] => 96
[type] => single
)
[3] => Array
(
[time] => 1364825753
[memberid] => 111
[type] => single
)
)
我的问题是:我想根据memberid和类型键搜索$ original数组中的匹配项,如果memberid和type不相同 - > gt;我想从$ original数组中删除该数组。所以在这种情况下我想保持[0]数组和[2]数组,因为在$ new数组中我有相同的memberid和相同的类型,但是我想删除[1]数组,因为memberid是相同的,但是类型不同。所以我的最终$原始数组将如下所示:
$original = Array (
[0] => Array
(
[time] => 1364690340
[memberid] => 90
[type] => single
)
[1] => Array
(
[time] => 1364690342
[memberid] => 96
[type] => single
)
)
答案 0 :(得分:2)
在这里,您只需对其进行测试,并按预期工作。
// Presuming your two arrays are still called $new & $original
$original = array(); // your data
$new = array(); // your data
$newArray = array();
foreach($original AS $key => $val){
$newArray[$val['memberid'] . '-' . $val['type']] = $val;
}
$original = array();
foreach($new AS $key => $val){
if(isset($newArray[$val['memberid'] . '-' . $val['type']])){
$original[] = $newArray[$val['memberid'] . '-' . $val['type']];
}
}
print_r($original);
答案 1 :(得分:-1)
如果没有对您的数据进行任何假设,那么这是一个效率低下的解决方案,如果 m 和 n,则为O( m * n ) 是数组的长度:
$new_original = array();
foreach ($original as $elem) {
// let's see if $new has something with the same type and memberid
foreach ($new as $candidate) {
if ($candidate['type'] == $elem['type'] &&
$candidate['memberid'] == $elem['memberid']) {
// it does! let's keep $elem
$new_original[] = $elem;
}
}
}
// reassign it to $original if desired
$original = $new_original;
但是,进行更有效的查找会更酷。例如,如果我们可以假设在$new
中最多只有一个元素具有给定的memberid:
// turn $new into a map
$new_as_map = array();
foreach ($new as $candidate) {
$new_as_map[$candidate['memberid']] = $candidate;
}
$new_original = array();
foreach ($original as $elem) {
if (isset($new_as_map[$elem['memberid']])) {
$candidate = $new_as_map[$elem['memberid']];
if ($candidate['type'] == $elem['type']) {
$new_original[] = $elem;
}
}
}
// reassign it to $original if desired
$original = $new_original;