PHP: re order associative array

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

    I like luky's answer the most but it requires specifying all of the keys. Most of the time you just want order a subset of the keys at the beginning of the array. This function will help then:

    function reorder_assoc_array(
      $cur,   // current assoc array 
      $order  // array conaining ordered (subset of) keys in $cur
    ) {
      $result = [];
      // first copy ordered key/values to result array
      foreach($order as $key) {
        $result[$key] = $cur[$key];
        // unset key in original array
        unset($cur[$key]);
      }
      // ... then copy all remaining keys that were not given in $order
      foreach($cur as $key => $value) {
        $result[$key] = $value;
      }
      return $result;
    }
    

    Example:

    $assoc_arr = [
      'b' => 'bbb',
      'a' => 'aaa',
      'c' => 'ccc',
      'd' => 'ffffd'
    ];
    
    // suppose we want to swap the first two keys and leave the remaining keys as is
    $assoc_arr = reorder_assoc_array($assoc_arr, ['a', 'b']);
    
    // ... the order of keys is now a, b, c, d
    

提交回复
热议问题