Circularly shifting associative array?

断了今生、忘了曾经 提交于 2019-12-10 22:04:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!