php基于值重复数组项

时间:2017-02-16 06:36:35

标签: php arrays

我有一个数组:

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

我希望新数组如下:

array([0] => adult,
      [1] => adult,
      [2] => child,
      [3] => infant);

4 个答案:

答案 0 :(得分:2)

这也有助于 -

$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

答案 1 :(得分: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

答案 2 :(得分:0)

你可以做一个foreach数组,并使用for循环它的值

第1步:

使用数组键值对进行foreach循环

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

第2步:

在Foreach循环中,执行for循环的值

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

第3步:

将for循环的$key值分配给新创建的数组

$newArray[] = $key;

<强>最后

<?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);

这里是Eval Link

答案 3 :(得分: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);
?>

输出:

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