通过键数组创建嵌套数组 [英] Create nested array by array of keys

查看:25
本文介绍了通过键数组创建嵌套数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在通过键数组创建嵌套数组并为最后一个嵌套项分配值时遇到了一些困难.

例如,让 $value = 4;$keys = ['a', 'b', 'c'];

最终结果应该是:

<预><代码>['a' =>['b' =>['c' =>4]]]

我尝试过递归,但没有成功.任何帮助将不胜感激.

解决方案

不需要递归,从右到左就行了:

$a = $value;for ($i = count($keys)-1; $i>=0; $i--) {$a = array($keys[$i] => $a);}

或者来自@felipsmartins 的更短版本:

$a = $value;foreach (array_reverse($keys) as $valueAsKey) $a = [$valueAsKey =>$a];

I've some difficulties creating a nested array by array of keys and assigning a value for the last nested item.

For example, lets $value = 4; and $keys = ['a', 'b', 'c'];

The final result should be:

[
  'a' => [
    'b' => [
      'c' => 4
    ]
  ]
]

I've tried with a recursion, but without success. Any help would be greatly appreciated.

解决方案

you don't need recursion, just do it from the right to left:

$a = $value;
for ($i = count($keys)-1; $i>=0; $i--) {
  $a = array($keys[$i] => $a);
}

or the even shorter version from @felipsmartins:

$a = $value;
foreach (array_reverse($keys) as $valueAsKey) $a = [$valueAsKey => $a]; 

这篇关于通过键数组创建嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆