Philipus Silaen Philipus Silaen - 6 months ago 18
PHP Question

print array value to txt

I write a program that have array printed in

txt
file:

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


The code above will produce a
txt
file:

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


but when I try to to print array from
DB
to
txt
by adopting the previous code, it doesn't give me desired output. Here is my code:

$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);


}

}


The code above give me
txt
file like below:

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


and the array from
$newResult
is:

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
)
}


My expected output:

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


Please help me, I don't know what's wrong with my code.

Answer

Use for loop outside the foreach loop, Will work for you..

<?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);
}
?>