我有一个随机洗牌的餐馆列表。我希望保持这种方式,除了将具有restaurant_id => 01
的特定项目移动到总是3rd
位置。我怎样才能做到这一点?
// Function to sort by open first
function sortByOrder($a, $b) {
return $a['open_status'] - $b['open_status'];
}
// randomize results
shuffle($data['list']);
$array = $data['list'];
// Sort by open first
usort($array, 'sortByOrder');
在代码中我将添加它以使特定名称始终位于第3位?
阵列是这样的:
array(30) {
[0]=>
array(3) {
["restaurant_id"]=>
string(1) "01"
["restaurant_name"]=>
string(7) "Place 1"
["open_status"]=>
string(1) "1"
}
[1]=>
array(3) {
["restaurant_id"]=>
string(1) "02"
["restaurant_name"]=>
string(7) "Place 2"
["open_status"]=>
string(1) "1"
}
...
}
所以基本上restaurant_id
= 01
的那个总是需要第3个。
答案 0 :(得分:0)
我建议将项目存储在临时变量中,从数组中删除项目,然后根据需要更改数组,然后重新插入。
<?php
$data = Array(
"list" => Array(1,2,3,4)
);
function sortByOrder($a, $b) {
return $a['open_status'] - $b['open_status'];
}
$temp = $data['list'][2]; //stores item
unset($data['list'][2]); //deletes item
shuffle($data['list']);
$array = $data['list'];
usort($array, 'sortByOrder');
array_splice($array, 2, 0, array($temp)); //re-insert the item
print_r($array);
?>