2016-02-05 74 views
0

我需要一個幫助。我需要在每次迭代中使用PHP將一個數組對象值推入另一個數組對象。我在下面解釋我的代碼。如何使用PHP將一個數組對象值推入循環內部

for($i=0;$i<$len;$i++){ 
while($report=mysqli_fetch_assoc($reportqry)){ 
     $result[]=$report; 
    } 
    //$arry 
} 

在這裏,我需要的$result將推入$arry在loop.Please的每次迭代中幫助我。

回答

0

使用array_push功能(PHP Manual

while($report=mysqli_fetch_assoc($reportqry)){ 
    array_push($result, $report); 
} 
+0

@ Wartus的結果:這裏$報告有什麼需要。 – subhra

+0

我在這裏需要'$ result'包含一些值的數組。所以我需要將這些數組的值移動到另一個數組對象。 – subhra

+0

@subhra $ report是您想要插入到數組中的值$ result – Berserk

0
$reportqry=mysqli_query(' some sql '); 

$len=5; 

$arry=array();/* was this defined before attempting to push items onto stack? */ 
$result=array();/* also define before loop */ 

for($i=0; $i < $len; $i++){ 
    while($report=mysqli_fetch_assoc($reportqry)){ 
     $result[]=$report; 
    } 
    $arry[]=$result; 
} 

我測試上面,它看起來像預期的那樣工作 - 但我不是100%肯定我已經掌握的概念。

我的測試:

$sql='select `username`,`description` from `tasks`'; 
$results=$conn->query($sql); 
$len=3; 

$arry=array(); 
$result=array(); 

for($i=0; $i < $len; $i++){ 
    while($rs=$results->fetch_assoc()){ 
     $result[]=$rs; 
    } 
    $arry[]=$result; 
} 

打印$arry

Array 
(
    [0] => Array 
     (
      [0] => Array 
       (
        [username] => fred 
        [description] => banana 
       ) 
      [1] => Array 
       (
        [username] => joe 
        [description] => apple 
       ) 
      [2] => Array 
       (
        [username] => bertrum 
        [description] => orange 
       ) 
     ) 
    [1] => Array 
     (
      [0] => Array 
       (
        [username] => fred 
        [description] => banana 
       ) 
      [1] => Array 
       (
        [username] => joe 
        [description] => apple 
       ) 
      [2] => Array 
       (
        [username] => bertrum 
        [description] => orange 
       ) 
     ) 
    [2] => Array 
     (
      [0] => Array 
       (
        [username] => fred 
        [description] => banana 
       ) 
      [1] => Array 
       (
        [username] => joe 
        [description] => apple 
       ) 
      [2] => Array 
       (
        [username] => bertrum 
        [description] => orange 
       ) 
     ) 
) 
+0

不,我檢查了它,但沒有正確顯示。 – subhra

+0

你想循環訪問記錄集$ len次並將多個副本添加到數組中嗎?爲什麼外部循環? – RamRaider

+0

'$ len'是一個數組中存在的多個id。假設在第一次迭代中使用第0個索引id多個數據presnt在'$ result'內,那麼它將作爲第0個索引返回到另一個數組類型對象,然後再次第2次迭代所有數據作爲第一個索引推入數組對象,等等...... – subhra

0

試試這個

for($i=0;$i<$len;$i++){ 
while($report=mysqli_fetch_assoc($reportqry)){ 

    array_push(result = $report); 
} 


//$arry 
}