0

I have an array with this:

array('adult'  => 2,
      'child'  => 1,
      'infant' => 1);

I want the new array to be like this:

array([0] => adult,
      [1] => adult,
      [2] => child,
      [3] => infant);
1
  • You should really say what you have tried and ask for help on how to sort it. Commented Feb 16, 2017 at 6:58

4 Answers 4

2

This would help also -

$arr = array('adult'  => 2, 'child'  => 1,'infant' => 1);

$result = [];
foreach ($arr as $key => $val) {
   $temp = array_fill(0, $val, $key); // fill array according to value
   $result = array_merge($result, $temp); // merge to original array
}

array_fill()

Working code

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

Comments

1
$arr = array('adult'  => 2, 'child'  => 1,'infant' => 1);

$result = [];  // declare variable to store final result
// Loop through array with value and keys 
foreach ($arr as $key => $val) {
     // Loop again till as per value of the Key
     // Will add that key in final array those many times.
     for ($i=0; $i<$val ; $i++) {
       $result[] = $key;
     }
}

print_r($result);  // will get desired output

1 Comment

Please add some explanations. It would help
0
<?php 
$array=array('adult'  => 2,
       'child'  => 1,
       'infant' => 1);
$final_array=[];

     foreach($array as $key=>$value){   

         for($i=0;$i<(int)$value;$i++){
            $final_array[]=$key; 
         }
     }
     echo "<pre>";
     print_r($final_array);
?>

Output:

Array
(
    [0] => adult
    [1] => adult
    [2] => child
    [3] => infant
)

Comments

0

You can do a foreach the array and use for loop with it's value

Step 1 :

Do a foreach loop with key value pair with your array

foreach($cars as $key => $value)
{
  //
}

Step 2 :

Inside the Foreach loop, do a for loop of it's value

for($i=0;$i<$value;$i++)
{
  //
}

Step 3 :

Assign the $key value of the for loop to your newly created array

$newArray[] = $key;

Finally

<?php
$cars = array('adult'  => 2,'child'  => 1,'infant' => 1);
$newArray = [];  // Create an Empty Array
foreach($cars as $key => $value)
{
    // Loop through the $value
    for($i=0;$i<$value;$i++)
    {
        $newArray[] = $key;
    }
}
print_r($newArray);

Here's the Eval Link

Comments

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.