PHP: re order associative array

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

    For a custom sorting, you can for example create an array that is the desired order of the keys and then associate the values with them. Example:

    $input = array("a"=>"Element A","b"=>"Element B","c"=>"Element C");
    $order = array("c","a","b");
    $out = array();
    foreach($order as $k) {
        $out[$k] = $input[$k];
    }
    

    The elements in $out will be in the order specified.

提交回复
热议问题