php为多维数组添加键和值

时间:2016-04-17 19:53:51

标签: php arrays multidimensional-array

我有这个数组

$additional = array();

如果我想为这个数组添加新的值和键,我使用

$additional["key"] = "value";

现在多维数组的问题

while($condition){
$this->array[] = array(
  "key" => "value"
    );

   //how can i add some key and value to this array 
   if($x == 1){
     $this->array[]["newkey"] = "value"; 
    }

   }
  

$ this-> array [] [“newkey”] =“value”;

我试试这个,但它不起作用

3 个答案:

答案 0 :(得分:1)

您必须为多维数组指定索引或键。

例如,您可以添加like;

$this->array[items]["newkey"] = "value"; 

答案 1 :(得分:1)

您可以使用增量变量:

<?php
$i = 0;
while($condition){
  $this->array[$i] = array(
    "key" => "value"
  );

  //how can i add some key and value to this array 
  if(x == 1){
     $this->array[$i]["newkey"] = "value"; 
  }
  $i++;
}
?>

答案 2 :(得分:1)

您可以延迟将嵌套数组添加到主数组中:

while($condition){
    $item = array(
        "key" => "value"
    );

    if(x == 1){
        $item["newkey"] = "value"; 
    }
    // When all is ready:
    $this->array[] = $item;
}