拆分字符串以形成多维数组键?

Cod*_*aft 2 php arrays

我正在从PHP数组创建JSON编码数据,这些数据可以是两个或三个级别,看起来像这样:

[grandParent] => Array (
                       [parent] => Array (
                                         [child] => myValue 
                                      )
                    )
Run Code Online (Sandbox Code Playgroud)

我所拥有的方法,只是在代码中手动创建嵌套数组,需要我通过键入一些可怕的嵌套数组来使用我的'setOption'函数(稍后处理编码),但是:

$option = setOption("grandParent",array("parent"=>array("child"=>"myValue")));
Run Code Online (Sandbox Code Playgroud)

我希望能够通过在这个实例中使用类似的javascript符号来获得相同的结果,因为我将在许多页面中设置许多选项,而上面只是不太可读,特别是当嵌套数组包含多个时键 - 虽然能够做到这一点会更有意义:

$option = setOption("grandParent.parent.child","myValue");
Run Code Online (Sandbox Code Playgroud)

任何人都可以通过在'.'上分割字符串来建议一种能够创建多维数组的方法.这样我可以将json_encode()转换为嵌套对象吗?

(setOption函数的目的是将所有选项一起收集到一个大的嵌套PHP数组中,然后再将它们全部编码,以便解决方案的去处)

编辑:我意识到我可以在代码中执行此操作:

$options['grandparent']['parent']['child'] = "myValue1";
$options['grandparent']['parent']['child2'] = "myValue2";
$options['grandparent']['parent']['child3'] = "myValue3";
Run Code Online (Sandbox Code Playgroud)

这可能更简单; 但是一个建议仍然会摇摆(因为我使用它作为更广泛的物体的一部分,所以它的$obj->setOption(key,value);

rjz*_*rjz 8

如果它们尚未创建并相应地设置键(这里是键盘),那么应该为您填充子数组:

function set_opt(&$array_ptr, $key, $value) {

  $keys = explode('.', $key);

  // extract the last key
  $last_key = array_pop($keys);

  // walk/build the array to the specified key
  while ($arr_key = array_shift($keys)) {
    if (!array_key_exists($arr_key, $array_ptr)) {
      $array_ptr[$arr_key] = array();
    }
    $array_ptr = &$array_ptr[$arr_key];
  }

  // set the final key
  $array_ptr[$last_key] = $value;
}
Run Code Online (Sandbox Code Playgroud)

这样称呼它:

$opt_array = array();
$key = 'grandParent.parent.child';

set_opt($opt_array, $key, 'foobar');

print_r($opt_array);
Run Code Online (Sandbox Code Playgroud)

为了与您的编辑保持一致,您可能希望将其调整为array在您的班级中使用...但希望这提供了一个开始的地方!