将PHP平面数组转换为嵌套数组,即将["a", "b", "c"]转换为["a" =>["b"=>["c"]]]。

23

正如示例中所述,我需要将一个扁平的数组嵌套,每个后续键都是前一个值。

示例:

array("I", "need", "this", "to", "be", "nested");
// To:
array("I" => array("need" => array("this" => array("to" => array("be" => array("nested"))))))
6个回答

23

以下是一种可能的实现:

<?php

function make_nested($array) {
    if (count($array) < 2)
        return $array;
    $key = array_shift($array);
    return array($key => make_nested($array));
}

print_r(make_nested(array("I", "need", "this", "to", "be", "nested")));

如果您不喜欢递归,这里提供了一个迭代版本:

function make_nested($array) {
    if (!$array)
        return array();
    $result = array(array_pop($array));
    while ($array)
        $result = array(array_pop($array) => $result);
    return $result;
}

17

使用array_reduce函数:

$a = ["I", "need", "this", "to", "be", "nested"];

$result = array_reduce(array_reverse($a), function($prevArray, $key){
    return $prevArray ? [$key => $prevArray] : [$key];
}, null);

请注意我们使用array_reverse,因为没有左规约。

工作示例:http://ideone.com/N61VtE


5

以下是一种只通过使用array_walk而不是创建新变量来修改原始数组的方法:

$a = ["I", "need", "this", "to", "be", "nested"];
array_walk(array_reverse($a), function ($v, $k) use (&$a) {
    $a = $k ? [$v => $a] : [$v];
});

如果$a为空,这应该只保留为空。但是,它假定您的输入数组从0开始具有键。

这太完美了!虽然我没有要求原地更改,但这似乎是我一直在寻找的最紧凑版本。 - Dead Man Walker
@DeadManWalker,实际上这不是最紧凑的版本。这是 我的回答中第一个函数的拼写:function mn($a) { return count($a) < 2 ? $a : [array_shift($a) => mn($a)]; }。此外,我的函数更高效。 - dened

4
我会使用一个 for 循环来实现这个:)
$array = array("I", "need", "this", "to", "be", "nested");

$newArray[$array[count($array)-2]] = array_pop($array);

for($i = count($array) - 2; $i > -1; $i--) {
  $newArray[$array[$i]] = $newArray;
  unset($newArray[$array[$i+1]]);
}

print_r($newArray);

3

运行代码

<?php

  // nested_array(array, start_index, length)
  function nested_array($arr, $i, $size)
  {
      if ($i == ($size-1))
      {
          return array($arr[$i] => array());
      }
      return array($arr[$i] => nested_array($arr,($i+1),$size));
  }

  print_r(nested_array(array("I", "need", "this", "to", "be", "nested"),0,6));

?>

4
OP希望他们最内层数组的形式看起来像array("be" => array("nested")),而你的代码返回的是Array([be] => nested)。顺便说一下,我认为一个空数组会更有意义,就像这样:["be" => ["nested" => []]] - Kobi

1
这似乎正在运行。

$a = array("I", "need", "this", "this", "to", "be", "nested");
$r = array($a[sizeof($a) - 1]);
for ($i=sizeof($a)-2; $i >= 0; $i--) { 
    $r = array($a[$i] => $r);
}
echo($ar == $r);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接