我需要一点帮助,我有多个数组类别,我需要让每个数组中的最后一个孩子进入
0=>array(
"categoryName"=>"category1",
"categorySlug"=>"categorys1",
"categoryNested"=>array(
0=>array(
"categoryName"=>"category2",
"categorySlug"=>"categorys2",
"categoryNested"=>array(
0=>array(
"categoryName"=>"category3",
"categorySlug"=>"categorys3",
)
)
)
),
1=>array(
"categoryName"=>"category4",
"categorySlug"=>"categorys4",
"categoryNested"=>array()
),
示例:
需要获取category3(categoryName),category4(categoryName),数组是多维的
答案 0 :(得分:1)
你可以试试这个。
<?php
$a = array(0=>array(
"categoryName"=>"category1",
"categorySlug"=>"categorys1",
"categoryNested"=>array(
"categoryName"=>"category2",
"categorySlug"=>"categorys2",
"categoryNested"=>array(
"categoryName"=>"category3",
"categorySlug"=>"categorys3",
)
)
),
1=>array(
"categoryName"=>"category4",
"categorySlug"=>"categorys4",
"categoryNested"=>array()
));
$cats = array();
foreach ($a as $cat){
while (isset($cat["categoryNested"]) && count($cat["categoryNested"])){
$cat = $cat["categoryNested"];
}
$cats[] = $cat["categoryName"];
}
print_r($cats);
答案 1 :(得分:0)
另一种选择,使用匿名函数:
$lastElements = array();
$findLastElements = function ($array) use (&$lastElements, &$findLastElements) { //create anonymous function
foreach($array as $key => $value) { //loop trough the array
if (isset($value['categoryNested']) && !empty($value['categoryNested'])) {
call_user_func($findLastElements, $value);
} elseif(isset($value['categoryName'])) {
array_push($lastElements, $value['categoryName']);
}
}
};
$findLastElements($array); //call the function
print_r($lastElements); //print the result