2

我需要一点帮助,我有多个数组类别,我需要在每个数组中获取最后一个孩子

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),数组是多维的

4

2 回答 2

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);
于 2013-07-15T06:33:12.567 回答
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
于 2013-07-15T06:39:35.913 回答