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

后端 未结 23 2641
逝去的感伤
逝去的感伤 2020-11-22 03:45

I have an associative array in the form key => value where key is a numerical value, however it is not a sequential numerical value. The key is actually an I

23条回答
  •  温柔的废话
    2020-11-22 04:18

    There is an alternative way to change the key of an array element when working with a full array - without changing the order of the array. It's simply to copy the array into a new array.

    For instance, I was working with a mixed, multi-dimensional array that contained indexed and associative keys - and I wanted to replace the integer keys with their values, without breaking the order.

    I did so by switching key/value for all numeric array entries - here: ['0'=>'foo']. Note that the order is intact.

    'alfa',
        'baz'=>['a'=>'hello', 'b'=>'world'],
    ];
    
    foreach($arr as $k=>$v) {
        $kk = is_numeric($k) ? $v : $k;
        $vv = is_numeric($k) ? null : $v;
        $arr2[$kk] = $vv;
    }
    
    print_r($arr2);
    

    Output:

    Array (
        [foo] => 
        [bar] => alfa
        [baz] => Array (
                [a] => hello
                [b] => world
            )
    )
    

提交回复
热议问题