[英]PHP - Flattening an array
我有這樣的數組。
Array
(
[0] => Array
(
[category] => vegetable
[type] => garden
[children] => Array
(
[0] => Array
(
[name] => cabbage
)
[1] => Array
(
[name] => eggplant
)
)
)
[1] => Array
(
[category] => fruit
[type] => citrus
)
)
用PHP構造像這樣的結果數組的簡單方法是什么?
Array
(
[0] => Array
(
[category] => vegetable
[type] => garden
[name] => cabbage
)
[1] => Array
(
[category] => vegetable
[type] => garden
[name] => eggplant
)
[2] => Array
(
[category] => fruit
[type] => citrus
)
)
我目前正在為此尋求解決方案。
也許不是“美容”方式,而是類似的東西?
$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']);
}
}
您是否需要下層階級的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")
)));
實時版本: http : //ideone.com/0wO4wU
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.