php如何修改二维数组子数组的键值例如

红框里面的键值想修改成:应该如何操作 邀请大神帮忙解决
2024-12-20 03:58:12
推荐回答(2个)
回答1:

//第一种,改变原数组
$keys = array('aa','bb','cc','dd','ee');
foreach($array as $key=>$val)
{
    foreach($val as $k=>$v)
    {
        $array[$key][$keys[$k]] = $v;
        unset($array[$key][$k]);
    }
}

//第二种,生成一个新数组
$keys = array('aa','bb','cc','dd','ee');
$newArray = array();

foreach($array as $key=>$val)
{
    foreach($val as $k=>$v)
    {
        $newArray[$key] = array();
        $newArray[$key][$keys[$k]] = $v;
    }
}
?>

回答2:

array_slice($arr,1,-1);截取出来再改;
参考例子,完整写法:
$ar = array(
array(1 => 'a', 2 => 50, 3 => 60, 4 => 'long', 5 => 'zzz', 6 => 'kkk', 7 => 'ooo'),
array(1 => 'b', 2 => 60, 3 => 70, 4 => 'king', 5 => 'lll', 6 => 'ttt', 7 => 'ppp'),
array(1 => 'c', 2 => 70, 3 => 80, 4 => 'quit', 5 => 'qqq', 6 => 'xxx', 7 => 'ccc'),
);
$kname = array('StaffId', 'Wage', 'Name', 'Work', 'Type');

function foo(&$v, $k, $kname) {
$v = array_combine($kname, array_slice($v, 1, -1));
}

array_walk($ar, 'foo', $kname);
print_r($ar);

Array
(
[0] => Array
(
[StaffId] => 50
[Wage] => 60
[Name] => long
[Work] => zzz
[Type] => kkk
)

[1] => Array
(
[StaffId] => 60
[Wage] => 70
[Name] => king
[Work] => lll
[Type] => ttt
)

[2] => Array
(
[StaffId] => 70
[Wage] => 80
[Name] => quit
[Work] => qqq
[Type] => xxx
)

)