随机php多维数组并获取原始数组索引 [英] random php multi-dimensional array and get the original array index
问题描述
任何人都可以帮助我了解多维数组?我有一个想要在其中随机排列数组的数组,因此它的层次结构或索引值将被更改并且与数组的原始排列不同,例如:
Anyone can help me about multi dimensional arrays? I have an array that wanted to random arrays inside it, so therefore its hierarchy or there index value will be changed and different from the original arrangement of arrays, like:
这是原始数组
Array(
[0]=>Array(
[title] => 'Title 1'
[description] => 'description here'
)
[1]=>Array(
[title] => 'Title 2'
[description] => 'another description here'
)
[2]=>Array(
[title] => 'Title Here Again'
[description] => 'description here again'
)
)
这将是上面数组的原始结构,如果你随机它,假设这将是结果
That will be the original structure of the array above, and if you random it, let say this will be the outcome
这是随机数组
Array(
[0]=>Array(
[title] => 'Title 2'
[description] => 'another description here'
)
[1]=>Array(
[title] => 'Title 3'
[description] => 'another description again'
)
[2]=>Array(
[title] => 'Title 1'
[description] => 'description here'
)
)
如您所见,数组内的值在不同位置随机化,现在问题是我无法获得有关如何从随机中获取原始数组索引的确切逻辑 -> ( [0] )数组.就像值 'Title 1' 一样,它的原始索引是 [0],在它被随机化后变成 [2],但我仍然希望将 'Title 1' 分配给索引 [0].这是关于我如何随机化数组的简短 php 代码:
As you can see, values inside the arrays are being randomize at different positions, now the problem is i can't get the exact logic on how to get the original array index like this -> ( [0] ) from randomized arrays. Like the value 'Title 1' its original index is [0], and after it was random-ed it became [2] but still i wanted 'Title 1' being assigned to index [0]. Here's a short php code on how i randomized the arrays:
foreach (shuffleThis($rss->getItems()) as $item) {
foreach($item as $key=>$value){
if($key=='title'){
$title=$value;
}
if($key=='description'){
$description=$value;
}
}
}
function shuffleThis($list) {
if (!is_array($list)) return $list;
$keys = array_keys($list);
shuffle($keys);
$random = array();
foreach ($keys as $key) {
$random[] = $list[$key];
}
return $random;
}
只是想让他们的key
的原始数组索引被随机化.
Just wanted to get they key
s original array index from being random-ed.
谢谢!
推荐答案
如果我理解正确,您想更改元素的顺序但保留键.你可以通过一个小的修改来做到这一点:
If I understand you correctly, you want to change the order of the elements but preserve the keys. You can do that with a small modification:
function shuffleThis($list) {
if (!is_array($list)) return $list;
$keys = array_keys($list);
shuffle($keys);
$random = array();
foreach ($keys as $key) {
$random[$key] = $list[$key]; // CHANGE HERE that preserves the keys
}
return $random;
}
这篇关于随机php多维数组并获取原始数组索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!