将对组合成组[PHP /数组] [英] Combine pairs to groups [PHP / Arrays]
本文介绍了将对组合成组[PHP /数组]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在PHP数组中有成对的物品。示例:
I have pairs of items in an PHP array. Example:
<?php
$elements = array(
'tiger'=>'lion',
'car'=>'bike',
'lion'=>'zoo',
'truck'=>'plane'
);
?>
现在我想合并这些项目,以便所有以任何方式连接的项目都进入一个组。继续上面的示例:
Now I want to combine these items so that all items which are connected in any way go to one group. Continuation of the example above:
<?php
$groups = array(
0=>array('tiger', 'lion', 'zoo'),
1=>array('car', 'bike'),
2=>array('truck', 'plane'
);
?>
这是可以理解的吗?我实现了吗?
Is this understandable? How could I achieve this?
我正在寻找一个可以做到这一点的函数。
I'm looking for a function which does this.
推荐答案
<?php
$elements = array(
'tiger' => 'lion',
'car' => 'bike',
'lion' => 'zoo',
'truck' => 'plane'
);
$groups = array();
foreach ($elements as $key => $val) {
$appended = false;
foreach ($groups as &$group) {
if ($group[0] == $key) {
array_unshift($group, $val);
$appended = true;
break;
}
}
if (!$appended) {
$groups[] = array($val, $key);
}
}
var_dump($groups);
礼物:
array(3) {
[0]=>
array(3) {
[0]=>
string(3) "zoo"
[1]=>
string(4) "lion"
[2]=>
string(5) "tiger"
}
[1]=>
&array(2) {
[0]=>
string(4) "bike"
[1]=>
string(3) "car"
}
[2]=>
array(2) {
[0]=>
string(5) "plane"
[1]=>
string(5) "truck"
}
}
这篇关于将对组合成组[PHP /数组]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文