【问题标题】:Creating an instance of a php key-value pair without an array创建一个没有数组的 php 键值对的实例
【发布时间】:2009-11-25 09:34:56
【问题描述】:

我正在编写一个递归函数来构造一个多维数组。基本上问题如下:

function build($term){      
    $children = array();

    foreach ( $term->children() as $child ) {
        $children[] = build($child);
    }

    if(!count($children)){
        return $term->text();
    } else {
        return $term->text() => $children; //obviously, this doesn't work           
    }
}

想法?我知道我可以重写函数的结构以使其工作,但似乎没有必要这样做。

【问题讨论】:

    标签: php multidimensional-array key-value


    【解决方案1】:
    function build($term){          
        $children = array();
    
        foreach ( $term->children() as $child ) {
            $children += build($child);
        }
    
        if(!count($children)){
            return $term->text();
        } else {
            return array($term->text() => $children); //obviously, this doesn't work               
        }
    }
    

    根据我对这个问题的理解,它应该是这样的。

    追加递归并返回一个数组。

    编辑:顺便说一句,即使 count($children) ==0,您最好还是返回一个数组,这将使您的所有类型都内联。否则你可能会遇到各种各样的错误:

    if(!count($children)){
                return array($term->text() => null);
    

    【讨论】:

    【解决方案2】:

    数组是 PHP 必须提供的唯一键值对容器。所以如果你想让你的函数(可能是递归的或不是递归的)返回一个键值对,你必须使用一个数组。

    return array($term->text() => $children);
    

    【讨论】:

      【解决方案3】:

      你可以这样退货:

      return array($term->text() => $children);
      

      虽然不是你问的。我认为如果不以一种或另一种方式重写部分功能,您就无法做到这一点。

      【讨论】:

        猜你喜欢
        • 2019-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-13
        • 2016-07-29
        • 2022-01-12
        相关资源
        最近更新 更多