【问题标题】:PHP - Sort the merged & shuffled array with specific value as first array valuePHP - 使用特定值作为第一个数组值对合并和洗牌的数组进行排序
【发布时间】:2021-06-22 09:28:49
【问题描述】:

我有 3 个nested arrays,我使用array_merge 来合并它们,以及shuffle 来洗牌。

这些是我的数组:

$array_1 = [
    ['product_1_1', 300, 100],
    ['product_1_2', 300, 100],
    ['product_1_3', 300, 100],
    ['product_1_4', 300, 100],
    ['product_1_5', 300, 100],
];

$array_2 = [
    ['product_2_1', 300, 250],
    ['product_2_2', 300, 250],
    ['product_2_3', 300, 250],
    ['product_2_4', 300, 250],
    ['product_2_5', 300, 250],
];

$array_3 = [
    ['product_3_1', 300, 500],
    ['product_3_2', 300, 500],
    ['product_3_3', 300, 500],
    ['product_3_4', 300, 500],
    ['product_3_5', 300, 500],
];

我想要实现的是在完成shuffle 之后,它总是首先将其中一个值放入$array_1,以便打乱后的数组始终以其中一个值开头在$array_1

【问题讨论】:

  • 首先洗牌 $array_1,然后从其中移出第一项。之后将其余的与您的其他数组结合起来,将其随机排列,然后将您移出的项目再次添加到开头……
  • 感谢@CBroe 感谢您的评论。我会试试的。我是PHP 的新手,你看

标签: php arrays sorting shuffle array-merge


【解决方案1】:

这是一种方法。从 array_1 中选择一个随机索引并从数组中删除该元素。然后结合所有,合并和随机播放,以 array_unshift 结尾,这将在最终数组前面加上我们的随机 array_1 值。

<?php

$array_1 = [
    ['product_1_1', 300, 100],
    ['product_1_2', 300, 100],
    ['product_1_3', 300, 100],
    ['product_1_4', 300, 100],
    ['product_1_5', 300, 100],
];

$array_2 = [
    ['product_2_1', 300, 250],
    ['product_2_2', 300, 250],
    ['product_2_3', 300, 250],
    ['product_2_4', 300, 250],
    ['product_2_5', 300, 250],
];

$array_3 = [
    ['product_3_1', 300, 500],
    ['product_3_2', 300, 500],
    ['product_3_3', 300, 500],
    ['product_3_4', 300, 500],
    ['product_3_5', 300, 500],
];

$first = rand(0, floor(count($array_1))); 
$firstItem = $array_1[$first];
unset($array_1[$first]);
 
$merged = array_merge($array_1, $array_2, $array_3);
shuffle($merged);
array_unshift($merged, $firstItem);

【讨论】:

    猜你喜欢
    • 2018-03-12
    • 1970-01-01
    • 1970-01-01
    • 2021-04-17
    • 1970-01-01
    • 2014-09-16
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    相关资源
    最近更新 更多