将平面 PHP 数组转换为基于数组键的嵌套数组?

2024-01-02

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

$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] 

附言@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',
  '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);
}

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

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

$ancestors[] = 0;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将平面 PHP 数组转换为基于数组键的嵌套数组? 的相关文章