脚本宝典收集整理的这篇文章主要介绍了将平面PHP数组转换为基于数组键的嵌套数组?,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
$education['x[1]'] = 'Georgia Tech';
它需要转换为:
$education[1][0] = 'Georgia Tech';
这是一个输入数组的例子:
$education = array( 'x[1]' => 'Georgia Tech','x[1][1]' => 'Mechanical Engineering','x[1][2]' => 'Computer Science','x[2]' => 'Agnes Scott','x[2][1]' => 'ReligIoUs History','x[2][2]' => 'Women\'s Studies','x[3]' => 'Georgia state','x[3][1]' => 'Business Administration',);
$education => array( 1 => array( 0 => 'Georgia Tech',1 => array( 0 => 'Mechanical Engineering' ),2 => array( 0 => 'Computer Science' ),),2 => array( 0 => 'Agnes Scott',1 => array( 0 => 'ReligIoUs History' ),2 => array( 0 => 'Women\'s Studies' ),3 => array( 0 => 'Georgia State',1 => array( 0 => 'Business Administration' ),);
我的头撞在墙上几个小时,仍然无法使其工作.我想我一直在看它太久了.提前致谢.
附:它应该是完全可嵌套的,即它应该能够转换一个如下所示的键:
x[1][2][3][4][5][6]
P.P.S. @Joseph Silber有一个聪明的解决方案,但不幸的是,使用eval()不是一个选项,因为它是一个wordpress插件,wordpress社区正在试图消除eval()的使用.
/** * Give IT and array,and an array of parents,it will decent into the * nested arrays and set the value. */ function set_nested_value(array &$arr,array $ancestors,$value) { $current = &$arr; foreach ($ancestors as $key) { // To handle the original input,if an item is not an array,// replace it with an array with the value as the First item. if (!is_array($current)) { $current = array( $current); } if (!array_key_exists($key,$current)) { $current[$key] = array(); } $current = &$current[$key]; } $current = $value; } $education = array( 'x[1]' => 'Georgia Tech',); $neweducation = array(); foreach ($education as $path => $value) { $ancestors = explode('][',substr($path,2,-1)); set_nested_value($neweducation,$ancestors,$value); }
基本上,将数组键分解成一个很好的祖先键,然后使用一个很好的函数,使用这些父对象进入$neweducation数组,并设置该值.
如果您想要更新您的帖子的输出,请在“explode”行之后的foreach循环中添加.
$ancestors[] = 0;
以上是脚本宝典为你收集整理的将平面PHP数组转换为基于数组键的嵌套数组?全部内容,希望文章能够帮你解决将平面PHP数组转换为基于数组键的嵌套数组?所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。