是否可以“提取”数组的前3个元素,然后将这3个元素混洗并将其添加回数组中?
这是一个滑块,前三个幻灯片应该在每个页面加载中随机显示...
有人可以帮忙吗?
public function shuffle( $data ) {
// Return early there are no items to shuffle.
if ( ! is_array( $data['slider'] ) ) {
return $data;
}
// Prepare variables.
$random = array();
$keys = array_keys( $data['slider'] );
// Shuffle the keys and loop through them to create a new, randomized array of images.
shuffle( $keys );
foreach ( $keys as $key ) {
$random[$key] = $data['slider'][$key];
}
// Return the randomized image array.
$data['slider'] = $random;
return $data;
}
/ * -----------------------更新--------------------- -* /
这是对我有用的方法,但是为什么呢?我对php相对陌生; D
public function shuffle($data) {
// Return early there are no items to shuffle.
if (!is_array($data['slider'])) {
return $data;
}
$sliced_array = array_slice($data["slider"], 0, 3, TRUE);
// Shuffle the keys and loop through them to create a new, randomized array of images.
shuffle($sliced_array);
$data['slider'] = $sliced_array + array_slice($data["slider"], 0);
return $data;
}
答案 0 :(得分:0)
<?php
$data = [1,2,3,4,5,6,7,8,9];
//get 3 first elements and remove 3 first elements from main array
$remains = array_splice($data,3);
//shuffle 3 elements
shuffle($data);
//join everything back
$data = array_merge(array_values($data), array_values($remains));
答案 1 :(得分:0)
是的,有可能。你走在正确的轨道上。经过一些调整,效果很好。
代码:
public function shuffling($data) {
// Return early there are no items to shuffle.
if (!is_array($data['slider'])) {
return $data;
}
$sliced_array = array_slice($data["slider"], 0, 3, TRUE);
// Shuffle the keys and loop through them to create a new, randomized array of images.
shuffle($sliced_array);
foreach ($sliced_array as $key => $value) {
$data['slider'][$key] = $value;
}
return $data;
}
我已经尝试过使用示例数组:
shuffling(["slider" => [
0 => "A",
1 => "B",
2 => "C",
3 => "D",
4 => "E",
]]);
结果是:
Array
(
[slider] => Array
(
[0] => B
[1] => C
[2] => A
[3] => D
[4] => E
)
)
注意:shuffle
已经在php中定义了功能。这就是为什么我将名称更改为shuffling
的原因。
答案 2 :(得分:0)
这是一个演示:https://3v4l.org/rYfV2
public function shuffler($data) {
// Return early there are no items to shuffle.
if (!is_array($data['slider'])) {
return $data;
}
// Generate a copy of first three elements.
$first = array_slice($data['slider'], 0, 3);
// Shuffle first three elements.
shuffle($first);
// Overwrite original first three elements.
$data['slider'] = array_replace($data['slider'], $first);
// $data['slider'] = $first + $data['slider']; // function-less alternative
// Return the randomized image array.
return $data;
}
array_replace()
避免以更冗长/重复的方式进行替换过程。当您只希望处理前三个元素时,它也避免处理整个数组。完全没有必要致电array_values()
。
您也可以使用并运算符代替array_replace()
-在array_replace()
行下查看我的注释代码行。 (Demo)
来自PHP Documentation Array Operator:
+运算符返回添加到左侧的右侧数组 数组对于两个数组中都存在的键, 将使用左侧数组,并且来自 右侧数组将被忽略。