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);
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);
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
}
$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
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