PHP递归版的功能有什么改进吗?

时间:2018-03-19 15:26:06

标签: php recursion

我创建了一个将转换数组的PHP函数:

[
    'one/two' => 3,
    'one/four/0' => 5,
    'one/four/1' => 6,
    'one/four/2' => 7,
    'eight/nine/ten' => 11,
]

进入以下JSON字符串:

{
    "one":
    {
        "two": 3,
        "four": [ 5,6,7]
    },
    "eight":
    {
        "nine":
        {
            "ten":11
        }
    }
}

这是功能:

<?php
function toJsonStr($array) {

    $final_array = [];

    foreach ($array as $key => $value) {

        $key_exploded = explode("/", $key);

        $array_index_at_end = is_numeric(end($key_exploded)) ? true : false ;

        if ($array_index_at_end === true) {
            $array_index = array_pop($key_exploded);
        }

        $ref = &$final_array;
        foreach ($key_exploded as $value2) {

            if (!isset($ref[$value2])) {
                $ref[$value2] = [];
            }

            $ref = &$ref[$value2];
        }

        if ($array_index_at_end === true) {
            $ref[$array_index]=$value;
        } else {
            $ref=$value;
        }
    }

    return json_encode($final_array);
}


$array = [
    'one/two' => 3,
    'one/four/0' => 5,
    'one/four/1' => 6,
    'one/four/2' => 7,
    'eight/nine/ten' => 11,
];

$json_str = toJsonStr($array);

echo "\n";
print_r($json_str);
echo "\n\n";

我几乎肯定这也可以递归地完成。我是递归的新手,在创建递归版本时遇到了构造方法的麻烦。

创建递归版本是否值得?与我上面实现的foreach中的简单foreach相比,它可能太难理解了吗?

我知道递归算法可以简化并使代码更紧凑,但在这种情况下它是否值得呢?

2 个答案:

答案 0 :(得分:1)

恕我直言,如果输入数组的结构可以具有嵌套结构,那么递归方法会有意义:

[
'one/two' => 3,
'one/four/0' => 5,
'one/four/1' => 6,
'one/four/2' => 7,
'eight/nine/ten' => 11,
'eleven/twelve' => [
  'thirteen/fourteen' => 15,
  'sixteen/seventeen' => 18,
  'nineteen/twenty' => [
    'twentyone/twentytwo' => 23
    ],
  ],
]

然后你应该为它实现一个递归函数。当你没有需要实施时,请保持简单。

答案 1 :(得分:1)

它可以更短,但我通常在没有递归的情况下这样做,因为它与深度无关。你已经掌握了参考文献。见How to access and manipulate multi-dimensional array by key names / path?

function toJsonStr($array, &$result=array()) {
    foreach($array as $key => $value) {
        $path = explode('/', $key);
        $temp =& $result;    
        foreach($path as $key) {
            $temp =& $temp[$key];
        }
        $temp = $value;
    }
    $result = json_encode($result);
}

toJsonStr($array, $result);