Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/270.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 动态构造数组_Php - Fatal编程技术网

Php 动态构造数组

Php 动态构造数组,php,Php,Hy 我有一个很大的问题。 我有一个这样的数组,$array[0]=12,$array[1]=20,$array[2]=18,基于这个数组,我想给这个数组赋值,因为我正在构建一个递归函数来创建一个包含大量子数组的多维数组 多谢各位 p.S.:如果我有一个$variable='[12][15][20],它会更简单吗;以某种方式创建$array{$variable}=value;因为我似乎不知道怎么做?老实说,我不能真正理解你的问题,因为我认为有很多不必要的信息模糊了你的实际问题 对于初学者,可以尝

Hy

我有一个很大的问题。 我有一个这样的数组,
$array[0]=12,$array[1]=20,$array[2]=18
,基于这个数组,我想给这个数组赋值,因为我正在构建一个递归函数来创建一个包含大量子数组的多维数组

多谢各位


p.S.:如果我有一个$variable='[12][15][20],它会更简单吗;以某种方式创建$array{$variable}=value;因为我似乎不知道怎么做?

老实说,我不能真正理解你的问题,因为我认为有很多不必要的信息模糊了你的实际问题

对于初学者,可以尝试以下代码:

function helper(&$array, $path, $value) {
  $parent =& $array;
  foreach ($path as $entry) {
    if (!isset($parent[$entry])) {
      $parent[$entry] = array();
    }

    $parent =& $parent[$entry];
  }

  $parent = $value;
  // make this $parent[] if more than
  // one $value will be added to the same path
}

$array_go = array(); // or use some other array you already have
helper($array_go, array(12, 20, 18), 1);
helper($array_go, array(12, 15, 20), 2);
helper($array_go, array(12, 10, 22), 3);

print_r($array_go);


/*
Array
(
    [12] => Array
        (
            [20] => Array
                (
                    [18] => 1
                )

            [15] => Array
                (
                    [20] => 2
                )

            [10] => Array
                (
                    [22] => 3
                )

        )

)
*/

不幸的是,答案的质量将与问题的质量成正比。@pufos根本不需要亵渎。你的未经编辑的问题对我来说也很难理解,因为代码示例让我迷惑不解。我知道这一点,但在问题结束时,我清楚地记得真正的问题是什么。因此,我编辑了问题并删除了不需要的部分:|这正是我想要的。。。对不起,我解释得模棱两可。我删除了它。如果我有一个$variable=
[12][15][20]
并以某种方式创建$array{$variable}=value,这是否简单;因为我似乎不知道该怎么做it@pufos您必须编写
$variable=array(12,15,20)
,然后可以将其作为第二个参数传递给helper-function。好的,我知道了,但是如果我有一个包含$arr键的$var,我就无法以某种方式向$arr+$keys=value添加一个值了吗?不,如果没有函数/类或任何东西的帮助,您将无法做到这一点。