我想从以下JSON数组中提取数据到我想用来创建文本文件的变量
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
)
)
我使用以下PHP,但只在我的文本文件中返回数组15的值。
$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);
答案 0 :(得分:1)
这是正常的,因为你在每次循环迭代时重置$ text!
也许试试这个:
$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);
答案 1 :(得分:0)
你正在重复每次迭代中$ text的值,因为@ zoubida13说。随着计数器的增加,文本值被更改为与该计数器对应的元素的串联。您可以尝试@ zoubida13提供的方法,或者您也可以使用FILE_APPEND作为file_put_contents中的第三个参数,代码将如下所示
` $ 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); $ filename =" output.txt&#34 ;;
foreach($ ticket_output_def as $ array){
$array0 = $array[0];
$array1 = $array[1];
$text = $array0 . $array1;
file_put_contents($filename, $text,FILE_APPEND);
}
`
但是,我认为这将是一种效率低下的方法,因为它每次都会尝试写入文件。最好在每次迭代中连接文本并在循环执行后写入它。
答案 2 :(得分:0)
我找到了解决方案。你必须使用PHP_EOL;预定义常量
$text = $text . $array0 . $array1 . PHP_EOL;