[英]PHP - Flattening an array
I have an array like this. 我有这样的数组。
Array
(
[0] => Array
(
[category] => vegetable
[type] => garden
[children] => Array
(
[0] => Array
(
[name] => cabbage
)
[1] => Array
(
[name] => eggplant
)
)
)
[1] => Array
(
[category] => fruit
[type] => citrus
)
)
What is an easy way to construct a resulting array like this using PHP? 用PHP构造像这样的结果数组的简单方法是什么?
Array
(
[0] => Array
(
[category] => vegetable
[type] => garden
[name] => cabbage
)
[1] => Array
(
[category] => vegetable
[type] => garden
[name] => eggplant
)
[2] => Array
(
[category] => fruit
[type] => citrus
)
)
I am currently working on a solution for this. 我目前正在为此寻求解决方案。
Maybe not the 'beauty' way, but just something like this? 也许不是“美容”方式,而是类似的东西?
$newArray = array();
foreach($currentArray as $item)
{
if(!empty($item['children']) && is_array($item['children']))
{
foreach($item['children'] as $children)
{
$newArray[] = array( 'category'=>$item['category'] , 'type'=>$item['type'] , 'name'=>$children['name']);
}
}
else
{
$newArray[] = array( 'category'=>$item['category'] , 'type'=>$item['type']);
}
}
Do you need children
down on your hierarchy? 您是否需要下层阶级的children
?
<?php
function transform_impl($arr, $obj, &$res) {
$res = array();
foreach ($arr as $item) {
$children = @$item['children'];
unset($item['children']);
$res[] = array_merge($obj, $item);
if ($children) {
transform_impl($children, array_merge($obj, $item), $res);
}
}
}
function transform($arr) {
$res = array();
transform_impl($arr, array(), $res);
return $res;
}
print_r(transform(array(
array("category" => "vegetable", "type" => "garden", "children" =>
array(array("name" => "cabbage"), array("name" => "eggplant"))
),
array("category" => "fruit", "type" => "citrus")
)));
Live version: http://ideone.com/0wO4wU 实时版本: http : //ideone.com/0wO4wU
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.