• Register

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
        )
)
版权声明:转载请注明来自杨俊伟博客,本文地址:http://yangjunwei.com/a/2691.html
除非注明,杨俊伟博客文章均为原创,转载请注明出处和链接!
 

发表评论 

我还是想用邮箱注册

登录

忘记密码 ?

用第三方帐号快捷登录

已有账户?前往登录吧~

注册