5

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

$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 和 type 键在 $original 数组中搜索匹配项,如果 memberid 和 type 不一样 -> 我想从 $original 数组中删除该数组。因此,在这种情况下,我想将 [0] 数组和 [2] 数组保留在 $new 数组中,我具有与原始数组相同的 memberid 和相同类型,但我想删除 [1] 数组,因为 memberid 是相同的,但是类型不同。所以我最终的 $original 数组将如下所示:

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

[1] => Array
    (
        [time] => 1364690342
        [memberid] => 96
        [type] => single
    )
)
4

2 回答 2

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);
于 2013-04-01T15:05:58.403 回答
-1

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

但是,进行更有效的查找会更酷。例如,如果我们可以假设在 中至多有一个具有给定 memberid 的元素$new

// 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;
于 2013-04-01T15:01:36.750 回答