I'm outputting a list of coordinates, and I want to automatically highlight the presence of duplicate coordinates.
<?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){
}
?>
Here's what the array looks like. You'll notice that the coordinates in some positions may be duplicated (ex. id #14
and #15
).
So the duplication will need to match on coordinates x/y/z
, but not on id.
I can not figure out how to get the values of the array as follows, and hide the duplicate:
7: 395x81x17
14: 115x47x21
14,15: 531x402x18
15: 528x207x24
15: 3x162x25
Why not just make kind of inverted index? Like
$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;
}
}
As result you will get $inverted_index
which can be used to display what you want to get
foreach ($inverted_index as $coords => $index){
printf("%s: %s
", implode(',', $index), $coords);
}
Or just access all coordinate points with simple $inverted_index[sprintf('%sx%sx%s', $x, $y, $z)]
.
The solution isn't memory friendly and building index each time isn't good idea but this looks quite simple to implement and use.