問題描述
我正在嘗試對數組中的數據運行清理作業,特別是將紀元時間轉換為 YYYY-MM-DD.
我最初嘗試過這個功能:
foreach ($data as $row) {$row['eventdate'] = date('Y-m-d', $row['eventdate']);}echo '';打印_r($數據);echo '</pre>';
但是,當我輸出數據時,foreach 循環并沒有更新數據.
以下 for 循環確實有效:
for ($i=0; $i
為什么第一個循環失敗而第二個循環成功?他們不一樣嗎?
當您以目前的方式使用 foreach
循環時,foreach ($data as $row){
, $row
被按值"使用,而不是按引用".
嘗試通過將 &
添加到 $row
來更新引用:
foreach ($data as &$row) {$row['eventdate'] = date('Y-m-d', $row['eventdate']);
或者,您可以使用鍵/值方法:
foreach ($data as $index => $row) {$data[$index]['eventdate'] = date('Y-m-d', $row['eventdate']);
I'm trying to run a clean up job on data in an array, specifically converting epoch time to YYYY-MM-DD.
I tried this function originally:
foreach ($data as $row) {
$row['eventdate'] = date('Y-m-d', $row['eventdate']);
}
echo '<pre>';
print_r($data);
echo '</pre>';
However the foreach loop didn't update the data when I output it.
The following for loop did work:
for ($i=0; $i<count($data); $i++) {
$data[$i]['eventdate'] = date('Y-m-d', $data[$i]['eventdate']);
}
Why did the first loop fail and the second work? Aren't they the same?
When you're using a foreach
loop in the way you currently are, foreach ($data as $row) {
, $row
is being used "by-value", not "by-reference".
Try updating to a reference by adding the &
to the $row
:
foreach ($data as &$row) {
$row['eventdate'] = date('Y-m-d', $row['eventdate']);
Or, you can use the key/value method:
foreach ($data as $index => $row) {
$data[$index]['eventdate'] = date('Y-m-d', $row['eventdate']);
這篇關于為什么我不能用 foreach 循環更新數組中的數據?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!