0

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.

2
  • What you want to create exactly ? can you provide details correctly ? From above array to below array or from below array to above ? Commented Mar 27, 2017 at 12:25
  • And where are you stuck? I highly doubt that this array conversion is useful at all. But this should be solveable all by your self. Hint: for-loop ... Commented Mar 27, 2017 at 12:28

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

What is the use of $pax?
my fault, copy/paste error. now it should be correct :)
0
$result = [];
$counter = 1;
foreach($passengers as $key=>$value)
{
  for($i=0;$i<$value;$i++)
  {
      $result[$key][] = $counter;
      $counter++;
  }   
}
print_r($result);

1 Comment

Whilst this code snippet is welcome, and may provide some help, it would be greatly improved if it included an explanation of how and why this solves the problem. Remember that you are answering the question for readers in the future, not just the person asking now! Please edit your answer to add explanation, and give an indication of what limitations and assumptions apply.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.