基于数组键将Flat PHP数组转换为嵌套数组?

Mik*_*kel 10 php multidimensional-array

我需要将数组键指示结构的平面数组转换为嵌套数组,其中父元素变为元素零,即在示例中:

$education['x[1]'] = 'Georgia Tech';
Run Code Online (Sandbox Code Playgroud)

它需要转换为:

$education[1][0] = 'Georgia Tech';
Run Code Online (Sandbox Code Playgroud)

这是一个示例输入数组:

$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',
);
Run Code Online (Sandbox Code Playgroud)

这是输出应该是什么:

$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' ),
  ),
);
Run Code Online (Sandbox Code Playgroud)

我把头撞在墙上好几个小时仍然无法让它工作.我想我已经看了太久了.提前致谢.

PS它应该是完全可嵌套的,即它应该能够转换如下所示的键:

x[1][2][3][4][5][6] 
Run Code Online (Sandbox Code Playgroud)

PPS @Joseph Silber有一个聪明的解决方案,但不幸的eval()是使用不是一个选项,因为它是一个WordPress插件和WordPress社区试图消除使用eval().

log*_*yth 5

下面是一些代码来处理您最初建议作为输出的内容。

/**
 * 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',
  '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',
);

$neweducation = array();

foreach ($education as $path => $value) {
  $ancestors = explode('][', substr($path, 2, -1));
  set_nested_value($neweducation, $ancestors, $value);
}
Run Code Online (Sandbox Code Playgroud)

基本上,将您的数组键拆分为一个很好的祖先键数组,然后使用一个很好的函数将这些父项放入 $neweducation 数组中,并设置该值。

如果您想要更新帖子的输出,请将其添加到 foreach 循环中的“explode”行之后。

$ancestors[] = 0;
Run Code Online (Sandbox Code Playgroud)