随机php多维数组并获取原始数组索引
有人能帮我了解多维数组吗?我有一个数组,它想要在其中随机排列数组,因此它的层次结构或索引值将改变,并且与数组的原始排列不同,如: 这是原始阵列随机php多维数组并获取原始数组索引,php,multidimensional-array,Php,Multidimensional Array,有人能帮我了解多维数组吗?我有一个数组,它想要在其中随机排列数组,因此它的层次结构或索引值将改变,并且与数组的原始排列不同,如: 这是原始阵列 Array( [0]=>Array( [title] => 'Title 1' [description] => 'description here' ) [1]=>Array( [title]
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'
)
)
这将是上面数组的原始结构,如果你随机选择它,那么这就是结果
这是随机排列的数组
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代码,介绍我如何对数组进行随机化:
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;
}
只是想让它们键
的原始数组索引不被随机分配
谢谢 使用字符串作为键,并使用函数“shuffle”。
洗牌示例:如果我理解正确,您希望更改元素的顺序,但保留键。只需稍加修改即可:
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;
}
哇!这是一个很好的答案,当我尝试它时,我可以看到元素在位置上发生了变化,但数组键却没有。但是我怎样才能得到像这样的键索引号[0],里面的零呢?不知道你在问什么。如何获取哪把钥匙,并提供哪些信息?