简体   繁体   English

如何对array_merge()函数的结果进行排序?

[英]How can I sort the result of array_merge() function?

Here is my code : 这是我的代码

<?php

$arr1 = ['o' => 'vote', 'u' => 'true'];
$arr2 = ['p' => '', 'v' => 'digit'];

print_r(array_merge($arr1, $arr2));

/* Array
   (
       [o] => vote
       [u] => true
       [p] => 
       [v] => digit
   )

Always there is one item which has empty value. 总是有一项具有空值。 In example above, that item is p . 在上面的示例中,该项目为p Now I need to put that item as the last one. 现在,我需要将该项目作为最后一项。 How can I do that? 我怎样才能做到这一点?

Note: I don't care about the order of other items. 注意:我不在乎其他项目的顺序。


So this is expected result: 因此,这是预期的结果:

/* Array
   (
       [o] => vote
       [u] => true
       [v] => digit
       [p] => 
   )

One possible approach that preserves the order of non-empty elements would be: 保留非空元素顺序的一种可能方法是:

$arr1 = ['o' => 'vote', 'u' => 'true'];
$arr2 = ['p' => '', 'v' => 'digit'];

$merged = $arr1 + $arr2;

$empty = array_filter($merged, function($var) {
    return $var == "";
});

$nonEmpty = array_diff_assoc($merged, $empty);

$sorted = $nonEmpty + $empty;
function sort($array){
        $emptyKey ="";
        foreach ($array as $key => $value){
             if(empty($value){
                  $emptyKey = $key;
                   break;
             }
        }
        unset($array[$emptyKey]);
        $array[$emptyKey] = "";
        return $array;
}

One simple way I found was to use rsort , which Sort an array in reverse order . 我发现的一种简单方法是使用rsort ,它以相反的顺序对数组进行排序 Like so ( run ): 像这样( 运行 ):

$merged = array_merge($arr1, $arr2);
rsort($merged);

The output: 输出:

Array
(
    [0] => vote
    [1] => true
    [2] => digit
    [3] => 
)

You could also go with a simple foreach ( example ) or even usort ( example ) 您也可以使用简单的foreach( 示例 )甚至usort示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM