Bart-Jan Arts Bart-Jan Arts - 6 months ago 36
PHP Question

extracting data from multidimensional array via PHP and store in text file

I would like to extract data from the following JSON arrays, to a variable that i would like to use to create a text file

Array
(
[0] => Array
(
[0] => 0
[1] =>
)

[1] => Array
(
[0] => 0
[1] => 123:
)

[2] => Array
(
[0] => 0
[1] => TICKET
)

[3] => Array
(
[0] => 0
[1] => ------------------------------------------------
)

[4] => Array
(
[0] => 1
[1] => user 1
)

[5] => Array
(
[0] => 1
[1] => info x
)

[6] => Array
(
[0] => 0
[1] => ------------------------------------------------
)

[7] => Array
(
[0] => 0
[1] => TEXT 1
)

[8] => Array
(
[0] => 0
[1] => TEXT 2
)

[9] => Array
(
[0] => 0
[1] => TEXT 4
)

[10] => Array
(
[0] => 1
[1] => TEXT 4
)

[11] => Array
(
[0] => 0
[1] => TEXT 5
)

[12] => Array
(
[0] => 0
[1] => TEXT 6
)

[13] => Array
(
[0] => 0
[1] => TEXT 7
)

[14] => Array
(
[0] => 0
[1] => TEXT 8
)

[15] => Array
(
[0] => 0
[1] => TEXT 9
)


)


I use the following PHP, but only the array 15 value is returned in my text file.

$ticket = file_get_contents('php://input');
$ticket_output = json_decode($ticket,true);

$ticket_output_def = $ticket_output['ticket'];

$ticket_output_txt = print_r($ticket_output_def,true);

foreach ($ticket_output_def as $array){

$array0 = $array[0];
$array1 = $array[1];

$text = $array0 . $array1;


}

$filename = "output.txt";

file_put_contents($filename, $text);

Answer

Well that's normal since you reset $text at every loop iteration!

Maybe try this :

$ticket = file_get_contents('php://input');
$ticket_output = json_decode($ticket,true);

$ticket_output_def = $ticket_output['ticket']; 

$ticket_output_txt = print_r($ticket_output_def,true); 
$text = "";
foreach ($ticket_output_def as $array){ 

    $array0 = $array[0];
    $array1 = $array[1];

    $text .= $array0 . $array1;


}

$filename = "output.txt";

file_put_contents($filename, $text);