将二维数组转换为多维
Posted
技术标签:
【中文标题】将二维数组转换为多维【英文标题】:Convert 2 dimensional array to multidimensional 【发布时间】:2012-08-15 06:36:49 【问题描述】:如何将此二维数组转换为树,即
这个
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 创建子代
【问题讨论】:
我认为这个答案可能有用:***.com/questions/4328515/… 【参考方案1】:代码:
/**
* 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
)
【讨论】:
以上是关于将二维数组转换为多维的主要内容,如果未能解决你的问题,请参考以下文章