PHP: re order associative array

后端 未结 7 758
难免孤独
难免孤独 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:12

    array_splice unfortunately doesn't work with associative arrays, so here's something a little messier:

    $keys = array_keys($arr);
    $values = array_values($arr);
    
    $keyIndex = array_search($someKey, $keys);
    array_splice($keys, $keyIndex, 1);
    array_splice($values, $keyIndex, 1);
    
    $insertIndex = 1;
    array_splice($keys, $insertIndex, 0, array($someKey));
    array_splice($values, $insertIndex, 0, array($arr[$someKey]));
    
    $arr = array_combine($keys, $values);
    

提交回复
热议问题