如何查找多数组内部之前找到的值

时间:2017-08-18 17:29:41

标签: php arrays find unique

我目前有以下问题。我必须检查数组是否包含完全相同的值以及之前是否找到它们。

int(3)之前没有找到,所以它是0, int(8)之前没有找到,所以它是0, int(5)之前没有找到,所以它是0, int(8)之前被发现所以它是1, int(3)和int(8)未找到,因此它为0,依此类推。

我已经尝试过使用array_unique但是没有按照我想要的方式工作

例如:

array(7) {
  [2] => array(1) {
    [0] => int(3)
  }
  [3] => array(1) {
    [0] => int(8)
  }
  [4] => array(1) {
    [0] => int(5)
  }
  [5] => array(1) {
    [0] => int(8)
  }
  [6] => array(2) {
    [0] => int(3)
    [1] => int(8)
  }
  [7] => array(2) {
    [0] => int(2)
    [1] => int(5)
  }
  [8] => array(2) {
    [0] => int(3)
    [1] => int(8)
  }
}

它必须看起来像这样

array(7) {
  [2] => array(1) {
    [0] => int(0)
  }
  [3] => array(1) {
    [0] => int(0)
  }
  [4] => array(1) {
    [0] => int(0)
  }
  [5] => array(1) {
    [0] => int(1)
  }
  [6] => array(1) {
    [0] => int(0)
  }
  [7] => array(1) {
    [0] => int(0)
  }
  [8] => array(1) {
    [0] => int(1)
  }
}

2 个答案:

答案 0 :(得分:0)

您可以使用array_map()serialize()

<?php

$data = [
    2 => [
        3,
    ],
    3 => [
        8,
    ],
    4 => [
        5,
    ],
    5 => [
        8,
    ],
    6 => [
        3,
        8,
    ],
    7 => [
        2,
        5,
    ],
    8 => [
        3,
        8,
    ],
];

$occurrences = [];

$mapped = array_map(function (array $values) use (&$occurrences) {
    // create serialized representation of the values
    // which we can use as an index 
    $index = serialize($values);

    // haven't seen these values before
    if (!array_key_exists($index, $occurrences)) {
        $occurrences[$index] = 1;

        return 0;
    }

    // increase our counter
    $occurrences[$index]++;

    return $occurrences[$index] - 1;
}, $data);

var_dump($mapped);

供参考,见:

有关示例,请参阅:

答案 1 :(得分:-1)

<?php
$new_array = array();
$indicator = array();
$current_array = array(
    "2" => array(3),
    "3" => array(8),
    "4" => array(5),
    "5" => array(8),
    "6" => array(3,8),
    "7" => array(2,5),
    "8" => array(3,8),
    );


foreach($current_array as $key => $value){
    if(!in_array($value, $new_array, true)){
        $new_array[$key] = $value;
        $indicator[$key] = false;
    } else {
        $indicator[$key] = true;
    }
}

var_dump($indicator);