【问题标题】:Highlight and hide duplicate values in a multidimensional array突出显示和隐藏多维数组中的重复值
【发布时间】:2016-03-02 08:54:22
【问题描述】:

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

<?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

【问题讨论】:

  • 你试过什么?/
  • 你的数据形状不好。 $coords = ["14" =&gt; [[115,47,21], [531,402,18]], "15" =&gt; [...], ...] 好多了。

标签: php arrays multidimensional-array duplicates


【解决方案1】:

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

$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)] 访问所有坐标点。

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

【讨论】:

  • 谢谢,这是我一直在寻找的解决方案。当然,它需要改进,但你帮助我取得了成果。
猜你喜欢
  • 2010-11-27
  • 2014-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-19
  • 2014-01-29
相关资源
最近更新 更多