Sort an Array by keys based on another Array?

后端 未结 15 846
甜味超标
甜味超标 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:45

    Take one array as your order:

    $order = array('north', 'east', 'south', 'west');
    

    You can sort another array based on values using array_intersect­Docs:

    /* sort by value: */
    $array = array('south', 'west', 'north');
    $sorted = array_intersect($order, $array);
    print_r($sorted);
    

    Or in your case, to sort by keys, use array_intersect_key­Docs:

    /* sort by key: */
    $array = array_flip($array);
    $sorted = array_intersect_key(array_flip($order), $array);
    print_r($sorted);
    

    Both functions will keep the order of the first parameter and will only return the values (or keys) from the second array.

    So for these two standard cases you don't need to write a function on your own to perform the sorting/re-arranging.

提交回复
热议问题