在随机位置开始数组,但遵循顺序
Start array at random position, but follow sequence
我目前拥有的是一个带有滑块图像链接的数组。目标是在数组中得到一个随机的起始位置,但是之后按照数组的顺序。
基本数组:1 2 3 4 5 6 7 8 9 10
随机开始:4 5 6 7 8 9 10 1 2 3
$attachments = get_children(
array(
'post_parent' => $attachment_holder['ID'],
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image',
'orderby' => 'rand'));
}
$attachments2 = get_children(
array(
'post_parent' => $attachment_holder['ID'],
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image',
'orderby' => 'rand'));
shuffle($attachments2);
$attachments2 = reset($attachments2);
$attachments2 = array($attachments2);
$attachments = array_merge($attachments2, $attachments);
上面只是输出随机的第一张图像,然后从规则序列开始。
所以:4 1 2 3 4 5 6 7 8 9 10
我觉得 array_chunk 或 array_slice 应该能帮助我,但我不太确定。
这样做:
<?php
$input = range(1, 20);
$start = array_rand($input);
$input = array_merge(array_slice($input, $start), array_slice($input, 0, $start));
print_r($input);
或就地:
<?php
$input = range(1, 20);
array_splice($input, 0, 0, array_splice($input, array_rand($input)));
print_r($input);
我目前拥有的是一个带有滑块图像链接的数组。目标是在数组中得到一个随机的起始位置,但是之后按照数组的顺序。
基本数组:1 2 3 4 5 6 7 8 9 10 随机开始:4 5 6 7 8 9 10 1 2 3
$attachments = get_children(
array(
'post_parent' => $attachment_holder['ID'],
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image',
'orderby' => 'rand'));
}
$attachments2 = get_children(
array(
'post_parent' => $attachment_holder['ID'],
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image',
'orderby' => 'rand'));
shuffle($attachments2);
$attachments2 = reset($attachments2);
$attachments2 = array($attachments2);
$attachments = array_merge($attachments2, $attachments);
上面只是输出随机的第一张图像,然后从规则序列开始。
所以:4 1 2 3 4 5 6 7 8 9 10
我觉得 array_chunk 或 array_slice 应该能帮助我,但我不太确定。
这样做:
<?php
$input = range(1, 20);
$start = array_rand($input);
$input = array_merge(array_slice($input, $start), array_slice($input, 0, $start));
print_r($input);
或就地:
<?php
$input = range(1, 20);
array_splice($input, 0, 0, array_splice($input, array_rand($input)));
print_r($input);