突出显示和隐藏多维数组中的重复值


Highlight and hide duplicate values in a multidimensional array

我正在输出一个坐标列表,我想自动突出显示重复坐标的存在。

<?php
$coords = array(
    "7" => array(
        "x" => array("0" => "395"),
        "y" => array("0" => "81"),
        "z" => array("0" => "17")
    ),
    "14" => array(
        "x" => Array("0" => "115","1" => "531"),
        "y" => Array("0" => "47","1" => "402"),
        "z" => Array("0" => "21","1" => "18")
    ),
    "15" => array(
        "x" => array("0" => "528","1" => "3","2" => "531"),
        "y" => array("0" => "207","1" => "162","2" => "402"),
        "z" => array("0" => "24","1" => "25","2" => "18")
    )
);
foreach ($coords as $index => $xyz){
}
?>

下面是数组的外观。您会注意到某些位置的坐标可能重复(例如 id #14#15 )。

所以重复需要在坐标x/y/z上匹配,而不是在id上匹配。

我无法弄清楚如何获取数组的值,如下所示,并隐藏重复项:

7: 395x81x17
14: 115x47x21
14,15: 531x402x18
15: 528x207x24
15: 3x162x25

为什么不做一种倒排索引呢?喜欢

$inverted_index = [];
foreach ($coords as $index => $xyz){
    for($i = 0; $i < count($xyz['x']); $i++) {
        $hash = sprintf('%sx%sx%s', $xyz['x'][$i], $xyz['y'][$i], $xyz['z'][$i]);
        if(!isset($inverted_index[$hash])) {
            $inverted_index[$hash] = [];
        }
        $inverted_index[$hash][] = $index;
    }
}

结果,您将获得可用于显示您想要获得的内容$inverted_index

foreach ($inverted_index as $coords => $index){
    printf("%s: %s'n", implode(',', $index), $coords);
}

或者只是用简单的$inverted_index[sprintf('%sx%sx%s', $x, $y, $z)]访问所有坐标点。

该解决方案对内存不友好,每次都构建索引不是好主意,但这看起来很容易实现和使用。