我需要转换一个平面数组,其中数组键将结构指示为一个嵌套数组,其中父元素变为零,即在示例中:
$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()的使用.
这里有一些代码来处理你最初提出的输出.
原文链接:https://www.f2er.com/php/132946.html/** * 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;