Shreyas Achar
Shreyas Achar

Reputation: 1435

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

if its $vehicle = 10 and $RequiredVehicle = 3 then Array value should be 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

Upvotes: 3

Views: 35

Answers (2)

Eddie
Eddie

Reputation: 26844

That is because you are just appending the $RequiredVehicle

You can use modulo % the $i and add 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
)

Upvotes: 1

Minar_Mnr
Minar_Mnr

Reputation: 1405

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
)

Upvotes: 0

Related Questions