将2维数组转换为多维数组

时间:2012-08-19 18:50:17

标签: php arrays multidimensional-array

如何将这个二维数组转换为树,即

:此

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => User
            [parent_id] => 0
        )

    [1] => Array
        (
            [id] => 2
            [name] => Product
            [parent_id] => 0
        )

    [2] => Array
        (
            [id] => 3
            [name] => Login
            [parent_id] => 1

        )

    [3] => Array
        (
            [id] => 4
            [name] => Forgot Password
            [parent_id] => 3

        )
}

Array
(

    [1] => User => Array
    (
        [3] => Login => Array
        (
            [4] => Forgot Password
        )
    }
    [2] => Product
}

即根据父ID

创建子项

1 个答案:

答案 0 :(得分:0)

代码:

/**
 * Convert tree array to custom tree
 * 
 * @param array $array given array
 * @param string $child_key child key name
 * @param type $id_key id key name
 * @param type $value_key value key name
 * @return array converted array
 */        
function toCustomSets(array $array, $child_key = 'items', $id_key = 'id', $value_key = 'name')
{
    $return = array();

    foreach ($array as $element) {
        if (count($element[$child_key])) {
            $return[$element[$value_key]] = array();
            $return[$element[$value_key]][$element[$id_key]] = $element[$value_key];
            $return[$element[$value_key]] = ($return[$element[$value_key]] + toCustomSets($element[$child_key]));
        } else {
            $return[$element[$id_key]] = $element[$value_key];
        }
    }

    return $return;
}
/**
 * Convert array to tree
 * 
 * @param array $array given array
 * @param int $parent_id parent id
 * @param string $parent_key parent id key name
 * @param string $id_key id key name
 * @return array converted array 
 */
function toTree(array $array, $parent_id = 0, $parent_key = 'parent_id', $id_key = 'id')
{
    $return = array();

    foreach ($array as $element) {
        if ($element[$parent_key] == $parent_id) {
            $element['items'] = toTree($array, $element[$id_key]);
            $return[] = $element;
        }    
    }

    return $return;
}

用法:

$data = array(
    array('id' => 1, 'name' => 'User', 'parent_id' => 0),
    array('id' => 2, 'name' => 'Product', 'parent_id' => 0),
    array('id' => 3, 'name' => 'Login', 'parent_id' => 1),
    array('id' => 4, 'name' => 'Forgot Password','parent_id' => 3));

$tree = toTree($data);
print_r(toCustomSets($tree));

输出:

Array
(
    [User] => Array
        (
            [1] => User
            [Login] => Array
                (
                    [3] => Login
                    [4] => Forgot Password
                )

        )

    [2] => Product
)