简体   繁体   English

Loop内部的Shuffle值和与数组连接

[英]Shuffle value inside Loop and concatenate with array

I do have a requirement where in Inside an array i need to shuffle the values. 我确实有一个要求,在一个数组里面我需要洗牌。

Below is the code Snippet 下面是代码片段

$vehicle = array('hcv','hcv','hcv','hcv','hcv','hcv','hcv','hcv','hcv','hcv');
$RequiredVehicle = 3;

$vehicleList = array();


for($i=0;$i<count($vehicle);$i++)
{
  $vehicleList[] =$vehicle[$i].$RequiredVehicle;
}

echo "<pre>";
print_r($vehicleList);

The Output what i am getting is 输出我得到的是

Array
(
    [0] => hcv3
    [1] => hcv3
    [2] => hcv3
    [3] => hcv3
    [4] => hcv3
    [5] => hcv3
    [6] => hcv3
    [7] => hcv3
    [8] => hcv3
    [9] => hcv3
)

The Actual output what i need is 我需要的实际输出是

Array
(
    [0] => hcv1
    [1] => hcv2
    [2] => hcv3
    [3] => hcv1
    [4] => hcv2
    [5] => hcv3
    [6] => hcv1
    [7] => hcv2
    [8] => hcv3
    [9] => hcv1
)

There are 10 vehicles and 3 Required vehicles so The output what i need is total vehicles should be shuffled between 3 Required vehicles 10辆车和3辆所需车辆所以我需要的输出是总车辆应该在3辆所需车辆之间洗牌

if its $vehicle = 10 and $RequiredVehicle = 3 then Array value should be 1,2,3,1,2,3,1,2,3,1 如果$ vehicle = 10且$ RequiredVehicle = 3则Array值应为1,2,3,1,2,3,1,2,3,1

if its $vehicle = 10 and $RequiredVehicle = 2 then Array value should be 1,2,1,2,1,2,1,2,1,2 如果它的$ vehicle = 10和$ RequiredVehicle = 2那么Array值应该是1,2,1,2,1,2,1,2,1,2

That is because you are just appending the $RequiredVehicle 那是因为你只是追加$RequiredVehicle

You can use modulo % the $i and add 1. Like ( ( $i % $RequiredVehicle ) + 1 ) 您可以使用模数% $i并添加1. Like ( ( $i % $RequiredVehicle ) + 1 )

$vehicle = array('hcv','hcv','hcv','hcv','hcv','hcv','hcv','hcv','hcv','hcv');
$RequiredVehicle = 3;

$vehicleList = array();
for($i=0;$i<count($vehicle);$i++)
{
   $vehicleList[] =$vehicle[$i] . ( ( $i % $RequiredVehicle ) + 1 );
}

echo "<pre>";
print_r($vehicleList);

This will result to: 这将导致:

Array
(
    [0] => hcv1
    [1] => hcv2
    [2] => hcv3
    [3] => hcv1
    [4] => hcv2
    [5] => hcv3
    [6] => hcv1
    [7] => hcv2
    [8] => hcv3
    [9] => hcv1
)

hopefully it will provide your actual output :) 希望它能提供你的实际输出:)

 $vehicle = array('hcv','hcv','hcv','hcv','hcv','hcv','hcv','hcv','hcv','hcv');
$RequiredVehicle = 3;

$vehicleList = array();

$j = 1 ;
for($i=0;$i<count($vehicle);$i++)
{

  $vehicleList[] =$vehicle[$i].$j++;
  if($j > $RequiredVehicle){
     $j=1;
}
}

echo "<pre>";
print_r($vehicleList);

Output: 输出:

Array
(
    [0] => hcv1
    [1] => hcv2
    [2] => hcv3
    [3] => hcv1
    [4] => hcv2
    [5] => hcv3
    [6] => hcv1
    [7] => hcv2
    [8] => hcv3
    [9] => hcv1
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM