我想在数组的一个键中包含多个键。我尝试了以下语法:<?phpfor($i = 0 ; $i < 3 ; $i++){ $str = 'name'.$i; if ($i == 0){ $date = 'today'; } elseif ($i == 1){ $date = 'yesterday'; } else{ $date = 'tomorrow'; } if ($date == "yesterday"){ $arr[] = ["user" => $str, "time" => '2020-10-2']; } elseif ($date == "today"){ $arr[] = ["user" => $str, "time" => '2020-10-3']; } elseif ($date == "tomorrow"){ $arr[] = ["user" => $str, "time" => '2020-10-4']; }}print_r($arr);但结果数组似乎只有一个元素。Array( [0] => Array ( [user] => name1 [time] => 2020-10-2 ))我不知道发生了什么事。感谢帮助。更新: 我分享这个是因为上面的代码显然没有显示我遇到的问题。这是实际的代码:<?php$txt_file = fopen('path.txt', 'r');$date = strtotime(fgets($txt_file));$arr = [];for($i = 0 ; !feof($txt_file) ; $i++){ $str = explode(':', fgets($txt_file)); if (count($str) != 2){ continue; } if ($str[1] == "yesterday"){ $arr[] = ["user" => $str[0], "time" => date("Y-m-d", $date-3600*24)]; } elseif ($str[1] == "today"){ $arr[] = ["user" => $str[0], "time" => date("Y-m-d", $date)]; } elseif ($str[1] == "tomorrow"){ $arr[] = ["user" => $str[0], "time" => date("Y-m-d", $date+3600*24)]; }}file_put_contents("INFO.json", json_encode($arr));fclose($txt_file);路径.txt 包含:3 October 2005quera1:todayquera2:tomorrowquera3:yesterdayquera4:today最终的 INFO.json 文件是:[{"user":"quera4","time":"2005-10-03"}]它只有最后一个元素。
1 回答
当年话下
TA贡献1890条经验 获得超9个赞
读取文件时fgets()
将包含输入中的新行,因此在尝试将其与文本进行比较时会出现尾随新行。用于trim()
删除任何多余的字符...
$str = explode(':', trim(fgets($txt_file)));
- 1 回答
- 0 关注
- 75 浏览
添加回答
举报
0/150
提交
取消