问题
Working in PHP, assume you have an associative array:
'Monday' => 'mon'
'Tuesday' => 'tue'
'Wednesday' => 'wed'
'Thursday' => 'thur'
'Friday' => 'fri'
'Saturday' => 'sat'
'Sunday' => 'sun'
How could you perform a "circular" array shift? Say shifting things so that the array starts with Wednesday, and proceeds through all 7 days, ending with Tuesday?
An important note: I need to do this by key, as I have other code determining what day the shift needs to start at.
回答1:
No looping required
$arr=array('Monday' => 'mon',
'Tuesday' => 'tue',
'Wednesday' => 'wed',
'Thursday' => 'thur',
'Friday' => 'fri',
'Saturday' => 'sat',
'Sunday' => 'sun');
//say your start is wednesday
$key = array_search("Wednesday",array_keys($arr));
$output1 = array_slice($arr, $key);
$output2 = array_slice($arr, 0,$key);
$new=array_merge($output1,$output2);
print_r($new);
回答2:
function curcle_shift($arr, $n) {
return array_slice($arr, $n % 7) + array_slice($arr, 0, $n % 7);
}
// ex. shift the first 2.
var_dump(curcle_shift($arr, 2));
回答3:
$key = array_keys($arr)[0]; // use a temporary variable in PHP before 5.4
$val = $arr[$key];
unset($arr[$key]);
$arr[$key] = $val;
This will take the first key, save its value, remove it from the array, then add it again (which will put it at the end of the array).
回答4:
Shifting an array while maintaining array keys:
function shiftArray($arr, $key) {
foreach ($arr as $k => $v) {
if ($k == $key) break;
unset($arr[$k]);
$arr[$k] = $v;
}
return $arr;
}
print_r(shiftArray($arr, 'Wednesday'));
/*
Array
(
[Wednesday] => wed
[Thursday] => thur
[Friday] => fri
[Saturday] => sat
[Sunday] => sun
[Monday] => mon
[Tuesday] => tue
)
*/
回答5:
Slice, merge, handle by reference.
function shiftArray( &$a, $k ) {
$k = array_search( $k, array_keys( $a ) );
$a = array_merge( array_slice( $a, $k ), array_slice( $a, 0, $k ) );
}
shiftArray( $week, "Wednesday" );
Since this works by reference, $week itself has been restructured. No new array.
Demo: http://codepad.org/uITGdMKy
回答6:
while (key($arr) !== $pivotKey) {
list($k, $v) = each($arr);
unset($arr[$k]);
$arr[$k] = $v;
}
make sure the key exists before entering the loop.
来源:https://stackoverflow.com/questions/10826760/circularly-shifting-associative-array