如何使用PHP

时间:2016-02-05 07:21:20

标签: php arrays loops

我需要一个帮助。我需要在每次迭代中使用PHP将一个数组对象值推送到另一个数组对象。我正在解释下面的代码。

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

在这里,我需要$result在循环的每次迭代中进入$arry。请帮助我。

3 个答案:

答案 0 :(得分:0)

使用array_push函数(PHP Manual

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

答案 1 :(得分: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
                )
        )
)

答案 2 :(得分:0)

试试这个

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

    array_push(result = $report);
}


//$arry
}