我有一个带有图形元素ID的输入数组,我需要找到它们的组。我试图使用array_search和array_marge但没有成功。
我有一系列兄弟姐妹:
'siblings' =>
array (size=6)
0 =>
array (size=2)
0 => int 0
1 => int 1
1 =>
array (size=2)
0 => int 2
1 => int 3
2 =>
array (size=2)
0 => int 3
1 => int 5
3 =>
array (size=2)
0 => int 4
1 => int 6
4 =>
array (size=2)
0 => int 4
1 => int 7
5 =>
array (size=2)
0 => int 6
1 => int 7
我需要输出如下:
'groups' =>
array (size=6)
0 =>
array (size=2)
0 => int 0
1 => int 1
1 =>
array (size=2)
0 => int 2
1 => int 3
2 => int 5
2 =>
array (size=2)
0 => int 4
1 => int 6
2 => int 7
我可以通过以下方式输出:
$groups[] = array_unique(array_merge($siblings[0]));
$groups[] = array_unique(array_merge($siblings[1],$siblings[2]));
$groups[] = array_unique(array_merge($siblings[3],$siblings[4],$siblings[5]));
var_dump($groups); // will output the previous output of groups
但我需要能够大规模运作的功能。
答案 0 :(得分:1)
可能效率不高但有效。通常的想法是遍历数组,检查当前与剩余内部数组的交集。如果有一些交集,只需将它们合并到当前,否则准备下一个数组(循环并提取下一组):
$a = array('siblings' => array(array(0,1),array(2,3),array(3,5),
array(4,6),array(4,7),array(6,7)));
$g[] = $a["siblings"][0];
$round = array_slice($a["siblings"],1);
$temp = array();
$i = 0;
while(count($round) > 0){
$v = array_shift($round);
if(count(array_intersect($g[$i],$v)) > 0)
$g[$i] = array_unique(array_merge($g[$i],$v));
else $temp[] = $v;
if(count($round) == 0 && count($temp) > 0) {
$g[] = $temp[0];
$i++;
$round = array_slice($temp,1);
$temp = array();
}
}
$groups["groups"] = $g;
var_dump($groups);
结果:
array(1) {
["groups"]=> array(3) {
[0]=> array(2) {
[0]=> int(0)
[1]=> int(1) }
[1]=> array(3) {
[0]=> int(2)
[1]=> int(3)
[3]=> int(5) }
[2]=> array(3) {
[0]=> int(4)
[1]=> int(6)
[2]=> int(7) } } }
答案 1 :(得分:0)
也许这样的事情会起作用。它不会将兄弟姐妹相互比较。相反,它会展平数组,删除重复项,然后将其分成3组。
<?php
$siblings = array(
array(0, 1),
array(2, 3),
array(3, 5),
array(4, 6),
array(4, 7),
array(6, 7),
);
$merged = array();
$grouped = array();
for ($i = 0; $i < count($siblings); $i++) {
array_push($merged, $siblings[$i][0]);
array_push($merged, $siblings[$i][1]);
}
$merged = array_unique($merged);
$merged = array_chunk($merged, 3);
print_r($merged);
?>
提供以下输出:
Array
(
[0] => Array
(
[0] => 0
[1] => 1
[2] => 2
)
[1] => Array
(
[0] => 3
[1] => 5
[2] => 4
)
[2] => Array
(
[0] => 6
[1] => 7
)
)