Sort an Array by keys based on another Array?

后端 未结 15 831
甜味超标
甜味超标 2020-11-22 03:29

Is it possible in PHP to do something like this? How would you go about writing a function? Here is an example. The order is the most important thing.

$custo         


        
15条回答
  •  渐次进展
    2020-11-22 03:39

    I adopted the answer from @Darkwaltz4 for its brevity and would like to share how I adapted the solution to situations where the array may contain different keys for each iteration like so:

    Array[0] ...
    ['dob'] = '12/08/1986';
    ['some_key'] = 'some value';
    
    Array[1] ...
    ['dob'] = '12/08/1986';
    
    Array[2] ...
    ['dob'] = '12/08/1986';
    ['some_key'] = 'some other value';
    

    and maintained a "master key" like so:

    $master_key = array( 'dob' => ' ' ,  'some_key' => ' ' );
    

    array_merge would have executed the merge in the Array[1] iteration based on $master_key and produced ['some_key'] = '', an empty value, for that iteration. Hence, array_intersect_key was used to modify $master_key in each iterations like so:

    foreach ($customer as $customer) {
      $modified_key = array_intersect_key($master_key, $unordered_array);
      $properOrderedArray = array_merge($modified_key, $customer);
    }
    

提交回复
热议问题