2016-02-05 69 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 
}