我确实需要在数组内部我需要对值进行随机化。
以下是代码段
$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);
我得到的输出是
Array
(
[0] => hcv3
[1] => hcv3
[2] => hcv3
[3] => hcv3
[4] => hcv3
[5] => hcv3
[6] => hcv3
[7] => hcv3
[8] => hcv3
[9] => hcv3
)
我需要的实际输出是
Array
(
[0] => hcv1
[1] => hcv2
[2] => hcv3
[3] => hcv1
[4] => hcv2
[5] => hcv3
[6] => hcv1
[7] => hcv2
[8] => hcv3
[9] => hcv1
)
有 10 车辆和 3 所需车辆所以我需要的输出是总车辆应该在3辆所需车辆之间洗牌
如果$ vehicle = 10且$ RequiredVehicle = 3那么Array值应为 的 1,2,3,1,2,3,1,2,3,1
如果$ vehicle = 10且$ RequiredVehicle = 2,那么Array值应为 的 1,2,1,2,1,2,1,2,1,2
答案 0 :(得分:1)
这是因为您只是追加$RequiredVehicle
您可以使用%
模$i
并添加1.赞( ( $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);
这将导致:
Array
(
[0] => hcv1
[1] => hcv2
[2] => hcv3
[3] => hcv1
[4] => hcv2
[5] => hcv3
[6] => hcv1
[7] => hcv2
[8] => hcv3
[9] => hcv1
)
答案 1 :(得分:0)
希望它能提供你的实际输出:)
$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);
输出:
Array
(
[0] => hcv1
[1] => hcv2
[2] => hcv3
[3] => hcv1
[4] => hcv2
[5] => hcv3
[6] => hcv1
[7] => hcv2
[8] => hcv3
[9] => hcv1
)