Php 是否可以将此阵列分组?
我有一个数组,我需要在一个多级数组中对这个数组进行排序。我试图按字段对它进行分组,但我可以使它工作。下面是我所拥有的阵列示例以及我想要的Php 是否可以将此阵列分组?,php,arrays,grouping,Php,Arrays,Grouping,我有一个数组,我需要在一个多级数组中对这个数组进行排序。我试图按字段对它进行分组,但我可以使它工作。下面是我所拥有的阵列示例以及我想要的 Array ( [0] => Array ( [id] => sports [title] => this is sports ) [1] => Array ( [id] => cricket
Array
(
[0] => Array
(
[id] => sports
[title] => this is sports
)
[1] => Array
(
[id] => cricket
[title] => this is cricket
[under] => sports
)
[2] => Array
(
[id] => batsman
[title] => this is batsman
[under] => cricket
)
[3] => Array
(
[id] => sachin
[title] => this is sachin
[under] => batsman
)
[4] => Array
(
[id] => football
[title] => this is football
[under] => sports
)
[5] => Array
(
[id] => ronaldo
[title] => this is ronaldo
[under] => football
)
)
我需要对这个数组进行分组,使其如下所示
Array(
[0] => Array(
[id] => Array(
[sports] => Array(
[cricket] => Array(
[batsman] => sachin
)
[football] => fun
)
)
)
)
我试过这样的东西,但不起作用
foreach($my_array as $item) {
//group them by under
$my_grouped_array[$item['under']][] = $item;
}
任何建议都很好。使用php对象:
function populateArray($my_array) {
//Populate the array
while ($my_array as $item) {
$array[$item->id]['id'] = $obj->id;
$array[$item->id]['name'] = $obj->name;
}
return $array;
}
$a = populateArray($array);
echo $a[0]['id'].'<br />';
echo $a[0]['name'].'<br />';
或者使用新的foreach我编写了一个递归函数,可以实现您想要的功能,但请记住,如果分支的最后一个元素不止一个,那么只会保存第一个元素 下面是函数:
function rearrange(&$result, $my_array, $element = NULL)
{
$found = 0;
$childs = 0;
foreach($my_array as $one) if(@$one['under'] == $element)
{
$found++;
if( ! is_array($result)) $result = array();
$result[$one['id']] = $one['id'];
$childs += rearrange($result[$one['id']], $my_array, $one['id']);
}
if( ! $childs AND is_array($result))
$result = reset($result);
return $found;
}
你可以这样称呼它:
$result = array(array('id' => array()));
rearrange($result[0]['id'], $my_array);
print_r($result);
我认为这是最直接的方法:
function getChildren($entry,$by_parent){
$children = array();
if (isset($by_parent[$entry['id']])){
foreach ($by_parent[$entry['id']] as $child){
$id = $child['id'];
$children[$id] = getChildren($child,$by_parent);
}
}
return $children;
}
$by_parent = array();
$roots = array();
foreach ($array as $entry){
if (isset($entry['under'])){
$by_parent[$entry['under']][] = $entry;
} else {
$roots[] = $entry;
}
}
$result = array();
foreach ($roots as $entry){
$id = $entry['id'];
$result[$id] = getChildren($entry,$by_parent);
}
$results = array(array('id'=>$results));
注意:这不是问题中指定的格式,但问题没有定义如何处理具有相同父节点的多个叶节点,而且这应该更容易遍历,因为它更一致。数组中的数据是否来自数据库?在这种情况下,更改查询可能会更简单。我使用preg_match_all从HTML内容中获取此数据,但不可能更改:这看起来不起作用,至少有两个原因$obj未定义和引用$item作为对象,即使它这样做了,它不会给出问题所要求的层次结构。$my_数组也是一个数组,而不是一个对象,即使可以将数组视为一个对象,它也不会具有这些属性。加上'as'是foreach的语法,在while循环中不起作用。即使你解决了所有这些问题,它仍然不能回答问题。