计算数组中的两个重复值和其他唯一值

时间:2017-02-21 07:05:47

标签: php arrays foreach iteration

我有一个10的多维数组,我想从这个数组中获取4条记录,但前2条记录应该有相同的dealer_id +其他2条记录是唯一的,可能是相同的。但是前2个应该有相同的dealer_id。如果数组中没有重复记录,那么所有4个记录都是不同的。所以任何关于什么是最快和最有效的方法的想法。

$array = array(array("_source" => array("dealer_id" => 2)),
    array("_source" => array("dealer_id" => 3)),
    array("_source" => array("dealer_id" => 2)),
    array("_source" => array("dealer_id" => 5)),
    array("_source" => array("dealer_id" => 7)),
    array("_source" => array("dealer_id" => 9)),
    array("_source" => array("dealer_id" => 8)),
    array("_source" => array("dealer_id" => 10)),
    array("_source" => array("dealer_id" => 12)),
    array("_source" => array("dealer_id" => 3)),
    array("_source" => array("dealer_id" => 12)));

我会试试这个。

$arr2 = array();
$counter = 0;
for ($arr = 0; $arr < count($array); $arr++) {

    if (in_array($array[$arr], $arr2)) {
        ++$counter;
        continue;
    } else {
        $arr2[] = $array[$arr];
    }
}
echo "<pre>";print_r($arr2);die;

1 个答案:

答案 0 :(得分:1)

您可以遍历数组,同时跟踪您在dealer_id索引的数组中已经看到的dealer_id。一旦你获得第一个副本,就会中断迭代并再获得2行(如果没有重复行,则为4行)。

$indexed_array = [];
$results = [];

foreach ($array as $e) {
    if (!isset($indexed_array[$e['_source']['dealer_id']])) {
        $indexed_array[$e['_source']['dealer_id']] = $e;
    }
    else {
        // add the 2 results with the same dealer_id to your results
        $results[] = $indexed_array[$e['_source']['dealer_id']];
        $results[] = $e;
        break;
    }
}


if (!empty($results)) {
    // get 2 more elements with a different dealer_id
    foreach ($array as $e) {
       if ($e['_source']['dealer_id'] != $results[0]['_source']['dealer_id']) {
          $results[] = $e;
          if (count($results) > 3) {
             break;
          }
       }
    }
}
else {
    // there are no duplicates so just get the 1st 4 elements
    $results = array_slice($array, 0, 4);
}

print_r($results);

Demo