我有一个值数组,我需要使用不同的哈希算法进行哈希,哈希类型数组包含所有哈希算法名称。
我想使用hash_rotation值从values数组中为每组值切换哈希算法,在这个例子中,我想为值数组的每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);
}
答案 0 :(得分:1)
听起来你需要利用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