一尘不染

PHP随机随机排列数组维护键=>值

php

我一直在谷歌上寻找答案,但似乎找不到一个万无一失的东西,而且真的负担不起将其弄乱(进入生产站点)。

我所拥有的是具有20多个过滤器的高级搜索,它返回一个包含ID和Distance的数组。我需要做的是将这些结果混洗以每次随机显示。目前我得到的数组是:

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和距离对,即:

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 )
)

谢谢 :)


阅读 227

收藏
2020-05-29

共1个答案

一尘不染

第一个用户后shuffle的文件:

在保留键,值对的同时,对关联数组和非关联数组进行混洗。还返回改组后的数组,而不是将其改组到位。

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));
2020-05-29