以下是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
)
始终有一个项目具有空值。在上面的示例中,该项目为p
。现在我需要将该项目作为最后一项。我怎样才能做到这一点?
注意:我不关心其他项目的顺序。
所以这是预期的结果:
/* Array
(
[o] => vote
[u] => true
[v] => digit
[p] =>
)
答案 0 :(得分:1)
保留非空元素顺序的一种可能方法是:
$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;
答案 1 :(得分:1)
function sort($array){
$emptyKey ="";
foreach ($array as $key => $value){
if(empty($value){
$emptyKey = $key;
break;
}
}
unset($array[$emptyKey]);
$array[$emptyKey] = "";
return $array;
}
答案 2 :(得分:1)
我发现的一种简单方法是使用How to transfer google cloud project ownership?,其中按相反顺序对数组进行排序。像这样(rsort):
$merged = array_merge($arr1, $arr2);
rsort($merged);
输出:
Array
(
[0] => vote
[1] => true
[2] => digit
[3] =>
)