PHP数组修改键名

一个二维数组修改键名的方法,记录一下。

看一下示例数组

$a2 = Array(
	"20170511" => Array(
			"aaa"	=> "2323",
			"bbb"	=> "5010",
			"ccc"	=> "102530",
			"ddd"	=> "100104",
		),
	"20170512" => Array(
			"aaa"	=> "2323",
			"bbb"	=> "5010",
			"ccc"	=> "102530",
			"ddd"	=> "100104",
		),
	"benqi" => Array(
			"aaa"	=> "3432323",
			"bbb"	=> "5010",
			"ccc"	=> "102530",
			"ddd"	=> "100104",
		),
	);

需求一:将键名 benqi 修改为当天的日期

使用的解决方案是将旧键名和值赋予给新键名,然后注销旧键名,代码如下:

$today = date("Ymd"); //20170513
$a2[$today] = $a2["benqi"];
unset( $a2["benqi"] );

// 输出示例
echo "<pre>";print_r($a2);echo "</pre>";

输出结果:

Array
(
    [20170511] => Array
        (
            [aaa] => 2323
            [bbb] => 5010
            [ccc] => 102530
            [ddd] => 100104
        )

    [20170512] => Array
        (
            [aaa] => 2323
            [bbb] => 5010
            [ccc] => 102530
            [ddd] => 100104
        )

    [20170513] => Array
        (
            [aaa] => 3432323
            [bbb] => 5010
            [ccc] => 102530
            [ddd] => 100104
        )

)

需求二:将键名 ddd 修改为 city

看代码:

foreach($a2 as &$a){
	$a['city'] = $a['ddd'];
	unset($a['ddd']);
}

// 输出示例
echo "<pre>";print_r($a2);echo "</pre>";

输出结果:

Array
(
    [20170511] => Array
        (
            [aaa] => 2323
            [bbb] => 5010
            [ccc] => 102530
            [city] => 100104
        )

    [20170512] => Array
        (
            [aaa] => 2323
            [bbb] => 5010
            [ccc] => 102530
            [city] => 100104
        )

    [20170522] => Array
        (
            [aaa] => 3432323
            [bbb] => 5010
            [ccc] => 102530
            [city] => 100104
        )
)