我已经有一个关联数组,里面已经有一堆数组。
我不想更改现有项目的相对顺序(关联数组中已经存在的数组),但是,我想以随机顺序(在现有项目之间)将新数组插入其中。我尝试了多种方法,但没有一种起作用。
PS:我写了一个可以将数组插入关联数组的函数,但是它总是将数组添加到关联数组的末尾。
protected function array_push_assoc(&$array, $key, $value){
$array[$key] = $value;
return $array;
}
例如:
原版的
array(
'apple'=>50,
'pear'=>10,
'banana'=>20
);
后:
array(
'apple'=>50, //<=== This remains the same relative order to pear and banana
'pear'=>10, //<=== This remains the same relative order to apple and banana
'something'=>15, //<===== this is randomly put in here.
'banana'=>20 //<=== This remains the same relative order to apple and pear
);
如果将来有人遇到相同的问题,可以的,这里是解决方案:
$random = rand(0, count($array) - 1);
$array = array_slice($array, 0, $random, true) + array($key => $value) + array_slice($array, $random, count($array) - 1, true);
这样就可以完成工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句