我创建了一个像
这样的数组$arr[0]['ref']=5;
$arr[0]['name']='name0';
$arr[1]['ref']=6;
$arr[1]['name']='name1';
$arr[2]['ref']=4;
$arr[2]['name']='name2';
$arr[3]['ref']='';
$arr[3]['name']='name3';
$arr[4]['ref']='9';
$arr[4]['name']='name4';
$arr[5]['ref']=''
$arr[5]['name']='name5'
我想用ref value
排序这个数组$arr[2]['ref']=4;
$arr[2]['name']='name2';
$arr[0]['ref']=5;
$arr[0]['name']='name0';
$arr[1]['ref']=6;
$arr[1]['name']='name1';
$arr[4]['ref']='9';
$arr[4]['name']='name4';
$arr[3]['ref']='';
$arr[3]['name']='name3';
$arr[5]['ref']=''
$arr[5]['name']='name5'
i tried
uasort($arr, function($a, $b){
return $a['ref'] - $b['ref'];
});
但是"值是从一开始就出现的。"我怎么能推下去呢?
提前感谢。我是初学者。请原谅,如果我问一个非常简单的问题
这就行了:
uasort($arr, function($a, $b){
if ($a['ref'] == "") return 1;
if ($b['ref'] == "") return -1;
return $a['ref'] - $b['ref'];
});
你可以试试
uasort($arr, function($a, $b){
return -($a['ref'] - $b['ref']);
});
可以在数组的末尾添加空值:
uasort($arr, function($a, $b){
return $a['ref'] - $b['ref'];
});
//strip empties and move to end
foreach ($arr as $key => $value)
{
if ($value['ref'] == "")
{
unset($arr[$key]);
$arr[] = $value;
}
}
// rebuild array index
$arr = array_values($arr);
输出:Array
(
[0] => Array
(
[ref] => 4
[name] => name2
)
[1] => Array
(
[ref] => 5
[name] => name0
)
[2] => Array
(
[ref] => 6
[name] => name1
)
[3] => Array
(
[ref] => 9
[name] => name4
)
[4] => Array
(
[ref] =>
[name] => name5
)
[5] => Array
(
[ref] =>
[name] => name3
)
)