Why can#39;t I update data in an array with foreach loop?(为什么我不能用 foreach 循环更新数组中的数据?)
问题描述
我正在尝试对数组中的数据运行清理作业,特别是将纪元时间转换为 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 循环更新数组中的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我不能用 foreach 循环更新数组中的数据?
				
        
 
            
        基础教程推荐
- php中的foreach复选框POST 2021-01-01
 - 主题化 Drupal 7 的 Ubercart “/cart"页 2021-01-01
 - Web 服务器如何处理请求? 2021-01-01
 - php中的PDF导出 2022-01-01
 - 如何在数学上评估像“2-1"这样的字符串?产生“1"? 2022-01-01
 - Yii2 - 在运行时设置邮件传输参数 2022-01-01
 - php 7.4 在写入变量中的 Twig 问题 2022-01-01
 - 使用 scandir() 在目录中查找文件夹 (PHP) 2022-01-01
 - PHPUnit 的 Selenium 2 文档到底在哪里? 2022-01-01
 - 将变量从树枝传递给 js 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
				
				
				
				