I have and array here is an example
0 apples
1 oranges
2 peaches
3 pears
4 watermelon
What I am looking to do is something like this
0 apples
2 peaches
4 watermelon
1 oranges
3 pears
It does not matter 开发者_开发技巧if the array keys change or not, I just need the location of the values.
<?php
$fruit = array('apples', 'oranges', 'peaches', 'pears', 'watermelon');
function fruitCmp($a, $b) {
if ($a == $b) {
return 0;
}
$aIsOdd = $a % 2;
$bIsOdd = $b % 2;
if (($aIsOdd && $bIsOdd) || (!$aIsOdd && !$bIsOdd)) {
return $a < $b ? -1 : 1;
}
if ($aIsOdd && !$bIsOdd) {
return 1;
}
if (!$aIsOdd && $bIsOdd) {
return -1;
}
}
uksort($fruit, 'fruitCmp');
var_dump($fruit);
Output:
array(5) {
[0]=>
string(6) "apples"
[2]=>
string(7) "peaches"
[4]=>
string(10) "watermelon"
[1]=>
string(7) "oranges"
[3]=>
string(5) "pears"
}
Hmm, try something like this:
<?php
$fruits = array('apples', 'oranges', 'peaches', 'pears', 'watermelon');
$odds = array();
$evens = array();
for($i = 0; $i < count($fruits); $i++){
if($i % 2){
$odds[] = $fruits[$i];
} else {
$evens[] = $fruits[$i];
}
}
?>
You will end up with two arrays, you can work on the odds as you wish, then combine the arrays (appending odds to evens with: $combined = $evens + $odds;).
many options, for example:
foreach($a as $n => $v)
$out[(($n & 1) << 24) | $n] = $v;
ksort($out);
or
foreach($a as $n => $v)
$out[$n & 1][] = $v;
$out = array_merge($out[0], $out[1]);
精彩评论