PHP 随机洗牌数组维护密钥 =>价值 [英] PHP Random Shuffle Array Maintaining Key => Value

查看:33
本文介绍了PHP 随机洗牌数组维护密钥 =>价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在 google 上寻找答案,但似乎无法找到一些万无一失的东西,而且真的不能把它搞砸(进入生产网站).

I've been looking on google for the answer but can't seem to find something fool-proof and cant really afford to mess this up (going live into a production site).

我拥有的是带有 20 多个过滤器的高级搜索,它返回一个包含 ID 和距离的数组.我需要做的是随机排列这些结果,每次都以随机顺序显示.我现在出来的数组是:

What I have is an advanced search with 20+ filters, which returns an array including an ID and a Distance. What I need to do is shuffle these results to display in a random order every time. The array I have that comes out at the moment is:

Array (
    [0] => Array ( [id] => 1 [distance] => 1.95124994507577 )
    [1] => Array ( [id] => 13 [distance] => 4.75358968511882 )
    [2] => Array ( [id] => 7 [distance] => 33.2223233233323 )
    [3] => Array ( [id] => 21 [distance] => 18.2155453552336 )
    [4] => Array ( [id] => 102 [distance] = 221.2212587899658 )
)

我需要做的是每次随机化或对这些进行排序,但要保持 id 和距离对,即:

What I need to be able to do is randomise or order of these every time but maintain the id and distance pairs, i.e.:

Array (
    [4] => Array ( [id] => 102 [distance] = 221.2212587899658 )
    [1] => Array ( [id] => 13 [distance] => 4.75358968511882 )
    [3] => Array ( [id] => 21 [distance] => 18.2155453552336 )
    [2] => Array ( [id] => 7 [distance] => 33.2223233233323 )
    [0] => Array ( [id] => 1 [distance] => 1.95124994507577 )
)

谢谢:)

推荐答案

第一篇用户帖子shuffle 文档下:

The first user post under the shuffle documentation:

随机关联和非关联数组同时保留键值对.还返回混洗数组而不是混洗它到位.

Shuffle associative and non-associative array while preserving key, value pairs. Also returns the shuffled array instead of shuffling it in place.

function shuffle_assoc($list) { 
  if (!is_array($list)) return $list; 

  $keys = array_keys($list); 
  shuffle($keys); 
  $random = array(); 
  foreach ($keys as $key) { 
    $random[$key] = $list[$key]; 
  }
  return $random; 
} 

测试用例:

$arr = array();
$arr[] = array('id' => 5, 'foo' => 'hello');
$arr[] = array('id' => 7, 'foo' => 'byebye');
$arr[] = array('id' => 9, 'foo' => 'foo');
print_r(shuffle_assoc($arr));
print_r(shuffle_assoc($arr));
print_r(shuffle_assoc($arr));

这篇关于PHP 随机洗牌数组维护密钥 =>价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆