删除多个数组中的重复键PHP

km0tfn4u  于 2022-12-10  发布在  PHP
关注(0)|答案(3)|浏览(123)

我有一个数组($datas),其中包含如下子数组:

我需要移除具有相同[0]值的子数组。但我无法执行此操作。
我测试了array_unique()和许多foreach在另一个foreach,但我不明白的方法(正确的英语?)。
欢迎您提出任何建议!

dwthyt8l

dwthyt8l1#

你所要做的就是在每个子数组的0中的值上重新索引主数组,它将删除重复的值:

$datas = array_column($datas, null, 0);

这对你来说应该是有用的,甚至更好地与新的索引。但如果你想回到原来的样子,只需要得到的值(没有必要):

$datas = array_values(array_column($datas, null, 0));
hk8txs48

hk8txs482#

好吧,我找到解决办法了!

$datasCounter = count($curlDatas["data"]); //datas counts

$subArrays = array_slice($datas, 0, $datasCounter);
foreach ($datas as $k => $v) {
    foreach ($subArrays as $key => $value) {
        if ($k != $key && $v[0] == $value[0]) {
            unset($subArrays[$k]);
        }
    }
}
0aydgbwb

0aydgbwb3#

这是一个使用Map的解决方案,我认为这是一个非常有效的解决方案,因为它不是像双foreach那样的O(n^2)复杂度,它只是O(n log n),它要快得多,我相信这是最快的复杂度。

// First, create an array of sub-arrays.
$arr = [
    [1, 2, 3],
    [1, 5, 6],
    [3, 3, 4],
    [1, 7, 8]
];

// We create a 'map' in PHP, which is basically just an array but with non-sequential (non-ordered) keys.
$map = [];

// We loop through all the sub-arrays and save the pair (first element, sub-array)
// since it's a 'map', it will only keep 1.
foreach($arr as $subarr)
{
  // The 'idx' is the first element (sub-array[0])
  $first = $subarr[0];
  // If you want the first appearance of the first element (in this case [1,2,3] for '1')
  // then you check if the first element of this sub-array was already found (is in the map)
  if (!array_key_exists($first, $map))
    $map[$first] = $subarr; // Set the 
}

// Now we convert the 'map' into an array with sequential keys,
// since the 'map' is just an array with non-sequential keys.
$arr = array_values($map);

// You can print the output.
print_r($arr);

这种情况下的输出将是:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [1] => Array
        (
            [0] => 3
            [1] => 3
            [2] => 4
        )
)

相关问题