简体   繁体   English

创建一个不带数组的php键/值对实例

[英]Creating an instance of a php key-value pair without an array

I'm writing a recursive function to construct a multidimensional array. 我正在编写一个递归函数来构建多维数组。 Basically, the problem is as follows: 基本上,问题如下:

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           
    }
}

Thoughts? 思考? I know I could rewrite the structure of the function to make it work, but it seems like that should be unnecessary. 我知道我可以重写该函数的结构以使其正常工作,但是似乎应该没有必要。

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               
    }
}

From what i understand of the question this is what it should look like. 根据我对问题的了解,这应该是什么样。

Appending the recursion and returning an array. 追加递归并返回一个数组。

Edit: as an aside you might be better off returning an array even if count($children) ==0, this would get all of your types inline. 编辑:顺便说一句,即使count($ children)== 0,您最好还是返回一个数组,这样可以内联所有类型。 else you may get all sorts of errors down the line: 否则您可能会得到各种各样的错误:

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

You could return it like this: 您可以这样返回:

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

Although it's not what you asked. 虽然这不是您要的。 I think you cannot do this without rewriting parts of your function, one way or another. 我认为,如果不以一种或另一种方式重写部分功能,就无法做到这一点。

An array is the only key-value pair container PHP has to offer. 数组是PHP必须提供的唯一键值对容器。 So you HAVE to use an array if you want your function (may it be recursive or not) to return a key-value pair. 因此,如果您想让函数(可能是递归的)返回键值对,就必须使用数组。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM