foreach
在写代码的过程中,发现foreach 有使用&的情况,还有使用索引的情况,这篇文章做一个总结
1.foreach 获取数组索引
PHP 的
foreach支持同时获取键(key)和值(value),语法如下:例如,当我们需要根据值判断并操作原数组时,可以通过 $key(即索引)直接修改或删除元素:
foreach ($nums as $i => $num){
if ($num === 0){
unset($nums[$i]);
$index++;
}
}
通过 $i 获取到当前数组的索引,=> 指向对应的值重要
$i 是当前元素的键(可能是数字索引,也可能是字符串键)
这种写法不需要引用符号 &,因为我们是通过 nums[i] 直接操作原数组
2.foreach 使用&
- 当我们希望直接修改数组中每个元素的内容(比如给每个子数组添加新字段),可以使用引用:
1. 使用&
foreach ($negative_feedback as &$row){
$res = Db::name("negative_feedback_order")
->field("online_paid, order_id,created_at,shop_name,delivery_poi_address,phone_list,deliver_fee,description,day_sn,income,total_price,consignee")
->where("negative_feedback_id", $row['id'])
->select()
->toArray();
$row["orders"] = $res;
}
unset( $ row);
因为 $row 默认是值的副本,不加 & 的话,$row["orders"] = ... 只会修改副本,
不会影响 $negative_feedback 原数组。2. 使用数组索引的方式
foreach ( $ negative_feedback as $ index => $ row) {
$ res = Db::name("negative_feedback_order")
->field("...")
->where("negative_feedback_id", $ row['id'])
->select()
->toArray();
// 通过索引写回原数组
$ negative_feedback[ $ index]['orders'] = $ res;
}重要
引用 & 虽然能直接修改元素,但容易引发隐蔽 bug(如忘记 unset 导致后续数据污染),而通过索引写回原数组更安全、更可读
版权所有
版权归属:念宇
