Hello stackoverflow社区。我需要有关数组的帮助。这是我的弱点。我有这种阵列:
vagrant ssh
我的工作是随机化具有相同Array
(
[0] => Array
(
[id] => 7
[slot] => 1
[name] => Apple
[start_date] => 12/16/2015
[end_date] => 03/10/2016
[status] => 1
[pre_exp_email] => 0
)
[1] => Array
(
[id] => 8
[slot] => 1
[name] => Cherry
[start_date] => 12/29/2015
[end_date] => 03/20/2016
[status] => 1
[pre_exp_email] => 0
)
[2] => Array
(
[id] => 5
[slot] => 3
[name] => Bananna
[start_date] => 11/30/2015
[end_date] => 00/00/0000
[status] => 1
[pre_exp_email] => 0
)
[3] => Array
(
[id] => 1
[slot] => 4
[name] => Kiwi
[start_date] => 11/21/2015
[end_date] => 12/21/2016
[status] => 1
[pre_exp_email] => 0
)
)
的元素,但保持顺序升序。例如现在是:
[slot]
我需要随机化那些具有相同插槽号的元素。所以Apple和Cherry将交换头寸。我怎么能这样做呢?
答案 0 :(得分:2)
更新:使用shuffle&我们:
shuffle($fruits);
function cmp($a, $b) {
if ($a['slot'] == $b['slot']) {
return 0;
}
return ($a['slot'] < $b['slot']) ? -1 : 1;
}
usort($fruits, "cmp");
答案 1 :(得分:1)
使用slot
作为键
$elements = array(
0 => Array
(
'id' => 7,
'slot' => 1
),
1 => Array
(
'id' => 8,
'slot' => 1
),
2 => Array
(
'id' => 9,
'slot' => 1
),
3 => Array
(
'id' => 9,
'slot' => 5
)
);
foreach($elements as $element){
$newArray[$element['slot']][] = $element; //put every element having the same slot
}
$elementSlots = array_keys($newArray); // all slots are stored in elementSlots
$Result = array();
foreach($elementSlots as $slot) {
shuffle($newArray[$slot]); //randomize elements having the same slot
foreach($newArray[$slot] as $element) { //add them to the result array
$Result[$slot][] = $element;//For output 1
//$Result[] = $element; //For output 2
}
}
var_dump($Result);
输出1:
array (size=2)
1 =>
array (size=3)
0 =>
array (size=2)
'id' => int 7
'slot' => int 1
1 =>
array (size=2)
'id' => int 9
'slot' => int 1
2 =>
array (size=2)
'id' => int 8
'slot' => int 1
5 =>
array (size=1)
0 =>
array (size=2)
'id' => int 9
'slot' => int 5
输出2:
array (size=4)
0 =>
array (size=2)
'id' => int 7
'slot' => int 1
1 =>
array (size=2)
'id' => int 9
'slot' => int 1
2 =>
array (size=2)
'id' => int 8
'slot' => int 1
3 =>
array (size=2)
'id' => int 9
'slot' => int 5