如果条件为true,则对上移的PHP数组进行排序
我有这样一个数组:如果条件为true,则对上移的PHP数组进行排序,php,Php,我有这样一个数组: [ [id: 1, urgent: true, marketplace: false], [id: 2, urgent: true, marketplace: true], [id: 3, urgent: false, marketplace: false] ] 数组的顺序是(默认)的,顶部有emergency。我需要的是向上移动所有具有marketplace=true的行 我尝试过这个,但不起作用: usort($f, function($a, $b) {
[
[id: 1, urgent: true, marketplace: false],
[id: 2, urgent: true, marketplace: true],
[id: 3, urgent: false, marketplace: false]
]
数组的顺序是(默认)的,顶部有emergency
。我需要的是向上移动所有具有marketplace=true
的行
我尝试过这个,但不起作用:
usort($f, function($a, $b) {
if ($a['marketplace'] || $b['marketplace']) {
return 1;
}
return 0;
});
试试这个:
usort($f, function($a, $b) {
if ($a['marketplace'] == $b['marketplace']) {
return 0;
}
return $a['marketplace'] ? 1 : -1;
});
marketplace为true的字段位于新数组的顶部。尝试结合您的条件:
您的意思是说
市场
的排序优先级高于紧急
,但如果两个项目具有相同的市场
值,紧急=真
应位于紧急=假
之前?
<?php
$data=[
['id'=> 1, 'urgent'=> true, 'marketplace'=> false],
['id'=> 2, 'urgent'=> true, 'marketplace'=> true],
['id'=> 3, 'urgent'=> false, 'marketplace'=> false],
['id'=> 3, 'urgent'=> false, 'marketplace'=> true],
['id'=> 3, 'urgent'=> false, 'marketplace'=> false],
['id'=> 3, 'urgent'=> false, 'marketplace'=> true],
['id'=> 3, 'urgent'=> false, 'marketplace'=> false],
];
echo"<pre>";
//print_r($data);
$trueArray=array();
$falseArray=array();
$i=0;
foreach($data as $row){
if($row['marketplace']==true){
$trueArray[$i]=$row;
}
else{
$falseArray[$i]=$row;
}
$i++;
}
//print_r($trueArray);
//print_r($falseArray);
$result=array_merge($trueArray,$falseArray);
print_r($result);
Array
(
[0] => Array
(
[id] => 2
[urgent] => 1
[marketplace] => 1
)
[1] => Array
(
[id] => 3
[urgent] =>
[marketplace] => 1
)
[2] => Array
(
[id] => 3
[urgent] =>
[marketplace] => 1
)
[3] => Array
(
[id] => 1
[urgent] => 1
[marketplace] =>
)
[4] => Array
(
[id] => 3
[urgent] =>
[marketplace] =>
)
[5] => Array
(
[id] => 3
[urgent] =>
[marketplace] =>
)
[6] => Array
(
[id] => 3
[urgent] =>
[marketplace] =>
)
)
usort( $arr, function ( $a, $b ) {
return ($a['urgent'] || $b['urgent']) && ($a['marketplace'] || $b['marketplace']);
} );