PHP: re order associative array

后端 未结 7 767
难免孤独
难免孤独 2020-12-10 15:37

In php, I would like to have the ability to re-order an associative array by moving elements to certain positions in the array. Not necessary a sort, just a re-ordering of

7条回答
  •  长情又很酷
    2020-12-10 16:06

    A lot of difficult methods here :) In fact, you can exploit the preserve keys feature of array_slice().

    $new_element = array('new_key' => 'value');
    
    // if needed, find the insertion index by key
    $index = array_search('key to search', array_keys($old_array));
    
    // add element at index (note the last array_slice argument)
    $new_array = array_slice($old_array, 0, $index+1, true) + $new_element + array_slice($old_array, $index+1, null, true);
    

提交回复
热议问题