欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

php 数组 array 修改键名键值 key 名 key 值 php array modify key name 有大用

In PHP, how do you change the key of an array element?


正确答案
foreach( $start_array as &$arr ) {
  $arr["x"] = $arr['date'];
  unset( $arr['date'] );
  $arr['y'] = $arr['revenue'];
  unset( $arr['revenue'] );
}
unset($arr);
来自 https://stackoverflow.com/questions/12574457/php-rename-the-keys-of-an-array


function rename_keys($array, $replacement_keys)  {
      return array_combine($replacement_keys, array_values($array));
}
$myarr = array("a" => 22, "b" => 144, "c" => 43);
$newkeys = array("x","y","z"); 
print_r(rename_keys($myarr, $newkeys)); 
//must return: array("x" => 22, "y" => 144, "z" => 43);



How to rename array keys in PHP?

When I var_dump on a variable called $tags (a multidimensional array) I get this:

Array
(
    [0] => Array
        (
            [name] => tabbing
            [url] => tabbing
        )

    [1] => Array
        (
            [name] => tabby ridiman
            [url] => tabby-ridiman
        )

    [2] => Array
        (
            [name] => tables
            [url] => tables
        )

    [3] => Array
        (
            [name] => tabloids
            [url] => tabloids
        )

    [4] => Array
        (
            [name] => taco bell
            [url] => taco-bell
        )

    [5] => Array
        (
            [name] => tacos
            [url] => tacos
        )
)

I would like to rename all array keys called "url" to be called "value". What would be a good way to do this?

 
 

8 Answers 正确答案

You could use array_map() to do it.

$tags = array_map(function($tag) {
    return array(
        'name' => $tag['name'],
        'value' => $tag['url']
    );
}, $tags);
shareimprove this answer
来自  https://stackoverflow.com/questions/9605143/how-to-rename-array-keys-in-php
普通分类: