从字符串创建数组 [英] Creating array from string

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

问题描述

我需要像这样创建数组:

Array('firstkey' => Array('secondkey' => Array('nkey' => ...)))

从这里:

firstkey.secondkey.nkey.(...)

推荐答案

$yourString = 'firstkey.secondkey.nkey';
// split the string into pieces
$pieces = explode('.', $yourString);
$result = array();
// $current is a reference to the array in which new elements should be added
$current = &$result;
foreach($pieces as $key){
   // add an empty array to the current array
   $current[ $key ] = array();
   // descend into the new array
   $current = &$current[ $key ];
}
//$result contains the array you want

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

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