我在使用foreach
关联数组数组时遇到麻烦,其中关联数组中的键是数字。
$rows = $_POST["row"];
// print_r($rows);
foreach ($rows as $r) {
fwrite($f, $r["date"]);
fwrite($f, "#");
fwrite($f, $r["desc-short"]);
fwrite($f, "#");
// etc.
}
POST 变量包含由 标识的数组row[index]
。如果我坚持,print_r()
它会按照它们在原始表单中出现的顺序显示 POST 值(这不一定是数字顺序,因为可以在中间插入行并且计数器表示它们何时添加,而不是添加位置),但是当我迭代foreach
它最后打印row[8]
(假设八行),即使它是在第 2 行之后插入的(例如)。
似乎因为我的键是数字,foreach
所以将键视为顺序。我怎样才能避免这种行为?
示例数据的输出print_r($rows)
:
Array ( [1] => Array ( [date] => 12/12/2013 [desc-short] => Show title [desc-long] => A sample long description [start-time] => 12:30 [duration] => 13 [rating] => TVY ) [2] => Array ( [date] => 12/12/2013 [desc-short] => TEST [desc-long] => TEST [start-time] => 12:45 [duration] => 14 [rating] => TVY ) [8] => Array ( [date] => 12/12/2013 [desc-short] => Calendar of Events [desc-long] => A list of local events displayed every hour on the hour [start-time] => 13:00 [duration] => 15 [rating] => TVY ) [3] => Array ( [date] => 12/12/2013 [desc-short] => Show title [desc-long] => A sample long description [start-time] => 12:45 [duration] => 12 [rating] => TVY ) [4] => Array ( [date] => 12/12/2013 [desc-short] => Calendar of Events [desc-long] => A list of local events displayed every hour on the hour [start-time] => 13:00 [duration] => 15 [rating] => TVY ) [5] => Array ( [date] => 12/12/2013 [desc-short] => Show title [desc-long] => test [start-time] => 13:15 [duration] => 100 [rating] => TVY ) [6] => Array ( [date] => 12/12/2013 [desc-short] => Calendar of Events [desc-long] => A list of local events displayed every hour on the hour [start-time] => 15:00 [duration] => 15 [rating] => TVY ) )
是的,7 不见了。我也得调查一下。第 1-6 行是从文件中加载的,而 [8] 是后来使用 JavaScript 在其中添加的。