将数组值打印到txt

时间:2016-05-28 10:42:47

标签: php arrays

我编写了一个在txt文件中打印过数组的程序:

$dataset   = array();
$dataset[] = array('A','B','C','D');
$dataset[] = array('A','D','C');
$dataset[] = array('B','C');
$dataset[] = array('A','E','C');
$arrLength=count($dataset);
for($x=0;$x<$arrLength;$x++){
        file_put_contents ('filename.txt', implode(',',$dataset[$x])."\n", FILE_APPEND);   
}

上面的代码将生成txt文件:

A,B,C,D
A,D,C
B,C
A,E,C

但是当我尝试通过采用前面的代码从DB打印数组到txt时,它并没有给我所需的输出。这是我的代码:

$result=array();
        $key='sub';
        foreach($this->Click_model->getClickStream() as $row)
        {

            $result[$row['id_click']]['sub'][]=  $row['id_kampanye'].$row['code'];
            $newResult=array_column($result,$key);
            file_put_contents ('datasetArray.txt', print_r($newResult, true));

            $arrLength=count($newResult);
            for($x=0;$x<$arrLength;$x++){

                file_put_contents ('dataset.txt', implode(',',$newResult[$x])."\n", FILE_APPEND);


            }

        }

上面的代码为我提供了txt文件,如下所示:

17p3
17p3,16visitor
17p3,16visitor
5visitor
17p3,16visitor
5visitor,18p3
17p3,16visitor
5visitor,18p3,15visitor
17p3,16visitor

来自$newResult的数组是:

Array
(
    [0] => Array
        (
            [0] => 17p3
            [1] => 16visitor
            [2] => 15visitor
            [3] => 17p3
            [4] => 5visitor
        )

    [1] => Array
        (
            [0] => 5visitor
            [1] => 18p3
            [2] => 15visitor
            [3] => 5visitor
            [4] => 18p3
            [5] => 10visitor
        )

    [2] => Array
        (
            [0] => 15visitor
            [1] => 15visitor
            [2] => 15visitor
            [3] => 15visitor
            [4] => 15visitor
            [5] => 15visitor
            [6] => 15visitor
            [7] => 15visitor
            [8] => 15visitor
        )
}

我的预期输出:

17p3,16visitor,15visitor,17p3,5visitor
5visitor,18p3,15visitor,5visitor,18p3,10visitor
15visitor,15visitor,15visitor,15visitor,15visitor,15visitor,15visitor,15visitor,15visitor

请帮助我,我不知道我的代码有什么问题。

2 个答案:

答案 0 :(得分:1)

在foreach循环之外使用for循环,对你有用..

<?php 
$result=array();
$key='sub';

foreach($this->Click_model->getClickStream() as $row)
{
    $result[$row['id_click']]['sub'][]=  $row['id_kampanye'].$row['code'];
    $newResult=array_column($result,$key);
    file_put_contents ('datasetArray.txt', print_r($newResult, true));
}

$arrLength=count($newResult);
for($x=0;$x<$arrLength;$x++)
{
    file_put_contents ('dataset.txt', implode(',',$newResult[$x])."\n", FILE_APPEND);
}
?>

答案 1 :(得分:0)

基于@Manjeet Barnala的评论,我已经为每个循环移动了循环,如下所示

ctrl+u