Reputation: 21
I need a little help, i have multi array categories, i need to get last children in in each array
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()
),
example:
need to get category3(categoryName),category4(categoryName), array is multidimensional
Upvotes: 2
Views: 315
Reputation: 2335
Another option, using a anonymous function:
$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
Upvotes: 0
Reputation: 24655
You can try this.
<?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);
Upvotes: 1