PHP和2多维数组基于两个键值进行比较



我有两个这样的多维数组:

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

我的问题是:我想搜索$original数组匹配基于memberid和类型键,如果memberid和类型不相同->我想从$original数组中删除该数组。所以在这种情况下,我想保留[0]Array和[2]Array,因为在$new Array中,我有相同的memberid和相同的类型,但我想删除[1]Array,因为memberid相同,但类型不同。那么最终的$original数组就是这样的:

$original = Array (
[0] => Array
    (
        [time] => 1364690340
        [memberid] => 90
        [type] => single
    )
[1] => Array
    (
        [time] => 1364690342
        [memberid] => 96
        [type] => single
    )
)

给你,刚刚测试了一下,效果和预期的一样。

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

在不对数据做任何假设的情况下,这里有一个低效的解决方案,如果mn是数组的长度,那么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;

相关内容

  • 没有找到相关文章

最新更新