2016-04-17 164 views
-2

我有這個陣列PHP添加鍵和值多維數組

$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"; 
    } 

    } 

$這 - >陣列[] [ 「則newkey」] = 「值」;

我嘗試這一點,但它沒有工作

+0

指定索引,如'陣列[0] [ 'newkey'] =' – trincot

+0

它的while循環如何知道索引可能我必須定義$ i = 0;出側循環,並增加每次有沒有另一個想法? –

回答

1

你可以延遲相加嵌套陣列到主陣列:

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

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

這就是我想要的很好回答:) –

1

你必須指定多維數組的索引或鍵。

例如,你可以添加像;

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

你可以使用一個incremential變量:

<?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++; 
} 
?> 
+0

它的while循環我怎麼知道索引可能我必須定義$ i = 0;出側循環,並增加每次有沒有另一個想法? –

+0

對不起,我不明白問題 – christophe

+0

在你的代碼沒有問題,但我想最好的主意和trincot寫它 –