Reputation: 3
I want this array
$passengers = array(
'adult' => 2,
'child' => 1,
'infant' => 1
);
to change like this. Create a sequence based on number of persons.
Array(
[adult] => Array(
[0] => 1
[1] => 2
)
[child] => Array(
[0] => 3
)
[infant] => Array(
[0] => 4
)
)
I'm stuck with this code
$seq=1;
foreach($passengers as $paxKey => $paxVal){
if($paxVal>1){
$pax[$paxKey][] = $seq;
$seq = $seq+$paxVal;
}else{
$seq=$paxVal+$seq;
$pax[$paxKey][] = $seq;
}
}
Any assistance is highly appreciated.
Upvotes: 0
Views: 68
Reputation: 121
$result = [];
$counter = 1;
foreach($passengers as $key=>$value)
{
for($i=0;$i<$value;$i++)
{
$result[$key][] = $counter;
$counter++;
}
}
print_r($result);
Upvotes: 0
Reputation: 8169
Try this:
$pax = [];
$seq = 1;
foreach($passengers as $key => $val){
while($val--) {
$pax[$key][] = $seq;
$seq++;
}
}
There are two cycles: the first one cycles the passengers, the second one creates as many elements as you need for each (kind of?) passenger.
Upvotes: 1