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

后端 未结 23 2374
逝去的感伤
逝去的感伤 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:23

    Simple benchmark comparison of both solution.

    Solution 1 Copy and remove (order lost) https://stackoverflow.com/a/240676/1617857

    for ($i =0; $i < 100000000; $i++){
        $array = ['test' => 'value'];
        $array['test2'] = $array['test'];
        unset($array['test']);
    }
    

    Solution 2 Rename the key https://stackoverflow.com/a/21299719/1617857

    for ($i =0; $i < 100000000; $i++){
        $array = ['test' => 'value'];
        $keys = array_keys( $array );
        $keys[array_search('test', $keys, true)] = 'test2';
        array_combine( $keys, $array );
    }
    

    Results:

    php solution1.php  6.33s  user 0.02s system 99% cpu 6.356  total
    php solution1.php  6.37s  user 0.01s system 99% cpu 6.390  total
    php solution2.php  12.14s user 0.01s system 99% cpu 12.164 total
    php solution2.php  12.57s user 0.03s system 99% cpu 12.612 total
    

提交回复
热议问题