插件窝 干货文章 PHP如何批量修改二维数组中值(五种方案)

PHP如何批量修改二维数组中值(五种方案)

name age gt class 593    来源:    2024-10-29

每个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);

到此这篇关于PHP如何批量修改二维数组中值的文章就介绍到这了,更多相关PHP批量修改二维数组内容请搜索插件窝以前的文章或继续浏览下面的相关文章希望大家以后多多支持插件窝!