PHP: re order associative array

后端 未结 7 736
难免孤独
难免孤独 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 15:52

    i made a function based on one answer here. it takes the array of assoc array to be sorted, plus array of keys in which it should be resorted

    // $data = array of assoc array
    // $newKeysOrder = array("c","a","b");
    function resort_assoc_array_by_keys($data, $newKeysOrder) {
      foreach($data as $v) {
        $out = [];
        foreach($newKeysOrder as $k) {
          $out[$k] = $v[$k];
        }  
        $new[] = $out;
      }
      return $new;
    }
    

提交回复
热议问题