在另一个数组中到达某个索引时移动数组索引

Move array index when a certain index is reached in another array

我有一个值数组,我需要使用不同的散列算法对其进行散列,散列类型数组包含所有散列算法名称。 我想使用 hash_rotation 值为值数组中的每组值切换哈希算法,在这种情况下,我想为值数组的每 3 个值切换 $hash_types,但是问题是当 $hash_types 数组用完时,我想回到它的第一个元素并使用它。

$hash_rotation = 3;

$hash_types = [
'type_1',
'type_2',
'type_3',
'type_4'
];

$values = [
'something goes 1',
'something goes 2',
'something goes 3',
'something goes 4',
'something goes 5',
'something goes 6',
'something goes 7',
'something goes 8',
'something goes 9',
'something goes 10',
'something goes 11'
];

$current_item = 0;

function rotate_hash($index) {

    global $hash_types;
    global $hash_rotation;
    global $current_item;

    if (($index) % $hash_rotation === 0) {
        $current_item++;
        if ($current_item >= count($hash_types))
            $current_item = 0;
    }

}

foreach ($values as $index => $value) {
    rotate_hash($index);
}

听起来您需要利用 next()current() 的数组指针操作:

$i  =   0;
# Loop values
foreach($values as $value) {
    # Get the current value of the hash
    $curr   =   current($hash_types);
    # If the count is equal or higher than what you want
    if($i >= $hash_rotation) {
        # Move the pointer to the next key/value in the hash array
        $curr   =   next($hash_types);
        # If you are at the end of the array
        if($curr === false) {
            # Reset the internal pointer to the beginning
            reset($hash_types);
            # Get the current hash value
            $curr   =   current($hash_types);
        }
    }
    # Increment
    $i++;

    echo $value.'=>'.$curr.'<br />';
}

给你:

something goes 1=>type_1
something goes 2=>type_1
something goes 3=>type_1
something goes 4=>type_2
something goes 5=>type_3
something goes 6=>type_4
something goes 7=>type_1
something goes 8=>type_2
something goes 9=>type_3
something goes 10=>type_4
something goes 11=>type_1