生成数组格式的函数:
function buildTree(array $elements, $parentId = 0) {
$branch = array();
foreach ($elements as $element) {
if ($element['parent_id'] == $parentId) {
$children = buildTree($elements, $element['id']);
if ($children) {
$element['children'] = $children;
}
$branch[] = $element;
}
}
return $branch;
}
$tree = buildTree($rows);
生成数组:
Array
(
[0] => Array
(
[TASK_ID] => 2
[PARENT_TASKID] => 0
[TASK_LEVEL] => 0
[children] => Array
(
[0] => Array
(
[TASK_ID] => 9
[PARENT_TASKID] => 2
[TASK_LEVEL] => 1
)
[1] => Array
(
[TASK_ID] => 10
[PARENT_TASKID] => 2
[TASK_LEVEL] => 1
)
)
)
[1] => Array
(
[TASK_ID] => 1
[PARENT_TASKID] => 0
[TASK_LEVEL] => 0
[children] => Array
(
[0] => Array
(
[TASK_ID] => 4
[PARENT_TASKID] => 1
[TASK_LEVEL] => 1
)
[1] => Array
(
[TASK_ID] => 5
[PARENT_TASKID] => 1
[TASK_LEVEL] => 1
[children] => Array
(
[0] => Array
(
[TASK_ID] => 6
[PARENT_TASKID] => 5
[TASK_LEVEL] => 2
)
)
)
)
)
)
如何将上述格式更改为:
Array
(
[0] => Array
(
[TASK_ID] => 2
[PARENT_TASKID] => 0
)
[1] => Array
(
[TASK_ID] => 9
[PARENT_TASKID] => 2
)
[2] => Array
(
[TASK_ID] => 10
[PARENT_TASKID] => 2
)
)
尝试下面的代码:
$flat = call_user_func_array('array_merge', $array);
和
$array = your array
$result = call_user_func_array('array_merge', $array);
echo "<pre>";
print_r($result);
但似乎没有用。请帮助。
感谢。
答案 0 :(得分:0)
<?php
$arr = array();
$i = 0;
foreach ($your_array[0] as $k => $v) {
if ($k == 'TASK_ID' OR $k == 'PARENT_TASKID') {
$arr[$i][$k] = $v;
}
$i++;
}
?>
尝试输出:
<?php
echo '<pre>';
print_r($arr);
echo '</pre>';
?>
希望,它适合你。
答案 1 :(得分:0)
我在捕获多个文件时一直用它来进行$ _FILES解析
function multi_array($array)
{
$new = array();
foreach($array as $key=>$elem)
{
if(is_array($elem))
{
foreach($elem as $x=>$val)
{
if(!is_array($val))
{
$new[$x][$key] = $val;
}
}
}
}
return $new;
}
用法很基本
$array = multi_array($array);
我希望它有所帮助
答案 2 :(得分:0)
尝试使用以下代码:
function makeOneDimensionArray(array $array, &$res = array())
{
foreach($array as $arr)
{
$res[] = array(
'TASK_ID' => $arr['TASK_ID'],
'PARENT_TASKID' => $arr['PARENT_TASKID']
);
if(isset($arr['children']))
{
makeOneDimensionArray($arr['children'], $res);
}
}
return $res;
}
$finalArr = makeOneDimensionArray($array);
print_r($finalArr);
我希望它有所帮助。
答案 3 :(得分:0)
您应该使用递归函数来展平树,因为您已使用递归函数来构建树。
function flattenTree($tree)
{
$flat = array();
foreach ($tree as $item) {
if (array_key_exists('children', $item)) {
$children = $item['children'];
unset($item['children']);
$flat[] = $item;
$flat = array_merge($flat, flattenTree($children));
} else {
$flat[] = $item;
}
}
return $flat;
}
$flat = flattenTree($tree);