每个name值加pex,age加5, 原数据:
$data=[
["name"=>'a','age'=>12],
["name"=>'b','age'=>22],
["name"=>'c','age'=>33],
["name"=>'d','age'=>44],
];
实现效果
方案一、foreach引用方式
$data=[
["name"=>'a','age'=>12],
["name"=>'b','age'=>22],
["name"=>'c','age'=>33],
["name"=>'d','age'=>44],
];
foreach ($data as &$v){
$v['name']="pex".$v['name'];
$v['age']=$v['age']+5;
}
var_dump($data);
方案二、foreach通过key改变原数组值
$data=[
["name"=>'a','age'=>12],
["name"=>'b','age'=>22],
["name"=>'c','age'=>33],
["name"=>'d','age'=>44],
];
foreach ($data as $k=>$v){
$data[$k]['name']="pex".$v['name'];
$data[$k]['age']=$v['age']+5;
}
var_dump($data);
方案三、使用传统的for循环修改数组元素:
$data = [
["name" => 'a', 'age' => 12],
["name" => 'b', 'age' => 22],
["name" => 'c', 'age' => 33],
["name" => 'd', 'age' => 44],
];
for ($i = 0; $i < count($data); $i++) {
$data[$i]['name'] = "pex" . $data[$i]['name'];
$data[$i]['age'] = $data[$i]['age']+5;
}
var_dump($data);
方案四、使用 foreach 循环副本修改数组元素:
$data = [
["name" => 'a', 'age' => 12],
["name" => 'b', 'age' => 22],
["name" => 'c', 'age' => 33],
["name" => 'd', 'age' => 44],
];
$newData = [];
foreach ($data as $item) {
$item['name'] = "pex" . $item['name'];
$item['age'] = $item['age']+5;
$newData[] = $item;
}
var_dump($newData);
方案五、使用 array_map 函数修改数组元素:
<?php
$data = [
["name" => 'a', 'age' => 12],
["name" => 'b', 'age' => 22],
["name" => 'c', 'age' => 33],
["name" => 'd', 'age' => 44],
];
$newData = array_map(function ($item) {
$item['name'] = "pex" . $item['name'];
$item['age'] = $item['age']+5;
return $item;
}, $data);
var_dump($newData);