php array random problem
$array = array(
array('name' => 'civilian 1'), //Random
array('name' => 'civilian 2'), //Random
array('name' => 'civilian 3'), //Random
array('name' => 'civilian 4'), //Random
array('name' => 'civilian 5'), //Random
array('name'=>'Rich', 'desc' => 'I am a Sponsor'), //Keep at the top
array('name'=>'Rich 2', 'desc' => 'I am a Sponsor'), //Keep at the top
);
if `desc has any string` will keep at the top
else if `desc is null` will random after `desc has any string`'s array
Example 1 Output
name: Rich
name: Rich 2
name: civilian 3
name: civilian 2
name: civilian 5
name: civilian 4
name: civilian 1
Example 2 Output
name: Rich
name: Rich 2
name: civilian 4
name: civilian 5
name: civilian 2
n开发者_StackOverflowame: civilian 1
name: civilian 3
Thanks a lot.
foreach ($array as $ppl) {
if ($ppl['desc']) $withDesc[] = $ppl;
else $without[] = $ppl;
}
shuffle($without);
$result = array_merge($withDesc, $without);
If you don't mind modifying your original array, this will work.
(also, don't put a semicolon (;
) after array members inside an array()
construct).
$array = array(
array('name' => 'civilian 1'),
array('name' => 'civilian 2'),
array('name' => 'civilian 3'),
array('name' => 'civilian 4'),
array('name' => 'civilian 5'),
array('name'=>'Rich', 'desc' => 'I am a Sponsor'),
array('name'=>'Rich 2', 'desc' => 'I am a Sponsor')
);
$newArray = array();
foreach($array as $index => $member) {
if (isset($member['desc'])) {
$newArray[] = $member;
unset($array[$index]);
}
}
shuffle($array);
$newArray = array_merge($newArray, $array);
Outputs...
array(7) {
[0]=>
array(2) {
["name"]=>
string(4) "Rich"
["desc"]=>
string(14) "I am a Sponsor"
}
[1]=>
array(2) {
["name"]=>
string(6) "Rich 2"
["desc"]=>
string(14) "I am a Sponsor"
}
[2]=>
array(1) {
["name"]=>
string(10) "civilian 5"
}
[3]=>
array(1) {
["name"]=>
string(10) "civilian 1"
}
[4]=>
array(1) {
["name"]=>
string(10) "civilian 4"
}
[5]=>
array(1) {
["name"]=>
string(10) "civilian 3"
}
[6]=>
array(1) {
["name"]=>
string(10) "civilian 2"
}
}
See it!
Create your own usort delegation function.
http://www.php.net/manual/en/function.usort.php
Return 1 when an element with a desc is being compared to an element without, and either 1, 0 or -1 when two elements with descs are being compared, based on the description text.
When two elements without descriptions are compared, return 1,0,-1 randomly, but make sure to store what random choice you made. It could be disastorous to return -1 when A and B are compared, but 1 next time they are compared. I'm not certain the usort algorithm employed in PHP would ever compare two elements twice, but it is definitely possible.
精彩评论