我正在尝试根据值将数组项移动到子数组中,例如:
Array
(
[0] => Array
(
[Desc] => 'Sub category'
[SubID] => null
)
[1] => Array
(
[Desc] => 'Listed item 1'
[SubID] => 1
)
[2] => Array
(
[Desc] => 'Listed item 2'
[SubID] => 1
)
[3] => Array
(
[Desc] => 'Item with no sub category'
[SubID] => null
)
)
会变成:
Array
(
[0] => Array
(
[Desc] => 'Sub category'
[SubID] => null
[SubSections] => Array
(
[Desc] => 'Listed item 1'
[SubID] => 1
)
[2] => Array
(
[Desc] => 'Listed item 2'
[SubID] => 1
)
)
[3] => Array
(
[Desc] => 'Item with no sub category'
[SubID] => null
)
)
很抱歉模糊,我不确定描述它的最佳方式,但希望上面的例子是有道理的。
谢谢!
答案 0 :(得分:2)
所以,我的解决方案可能不是最漂亮的,但它基于一个假设,即一个类别可能出现在数组中的一个子节点之后,因此我们首先计算出类别...然后再做一个循环来填充子类别
$arr = Array (
[0] => Array
(
[Desc] => 'Sub category'
[SubID] => null
)
[1] => Array
(
[Desc] => 'Listed item 1'
[SubID] => 1
)
[2] => Array
(
[Desc] => 'Listed item 2'
[SubID] => 1
)
[3] => Array
(
[Desc] => 'Item with no sub category'
[SubID] => null
) )
$new_arr = array();
// sort out the categories first foreach ($arr as $key => $item) {
foreach ($arr as $key => $item) {
if (is_null($itemp['SubID']))
{
$new_arr[$key] = array(
'Desc' => $item['Desc'],
'SubID' => null
);
unset($arr[$key]);
}
}
foreach ($arr as $key => $item) {
$new_arr[$key]['SubSections'][] = array(
'Desc' => $item['Desc'],
'SubID' => $item['SubID'] - 1
);
}
答案 1 :(得分:2)
我在数组[0] => title, [1] => parent
<?php
$arr = array(
1 => array( '1', 2),
2 => array( '2', 0),
3 => array( '3', 1),
4 => array( '4', 1),
);
$result = array();
foreach( $arr as $key => &$item){
// Root element
if( $item[1] == 0){
$result[] = &$item;
continue;
}
// Any other element
if( !isset( $arr[ $item[1]])){
die( 'Missing index');
}
// Initialize new child elements or append to existing list
if( !isset( $arr[ $item[1]][2])){
$arr[ $item[1]][2] = array( &$item);
} else {
$arr[ $item[1]][2][] = &$item;
}
}
print_r( $result);
警告:原始数组将被更改。
注意:我使用0作为根索引,而不是null ...实现了一个例子。
答案 2 :(得分:1)
<?
foreach($arr as $index=>$subArr){
if($subArr['SubID']){
$arr[$subArr['SubID']-1]['SubSections'][] = $subArr;
unset($arr[$index]);
}
}
?>
我认为这将完成这项工作。
可能隐含一些修饰答案 3 :(得分:1)
使用此
<?php
$array = array(
array('desc'=>'Sub Category 1','subid' => null),
array('desc' => 'list item 1','subid' => 1),
array('desc' => 'list item 2','subid' => 1),
array('desc'=>'Sub Category 2','subid' => null)
);
foreach ($array as $key => $val){
if ($val['subid']){
$sub_array = $val;
if (is_array($array[$val['subid']-1]['subsections'])){
$array[$val['subid']-1]['subsections'][] = $val;
}else{
$array[$val['subid']-1]['subsections'] = array($val);
}
unset($array[$key]);
}
}
print_r($array);
?>