2017-02-16 106 views
0

我有這樣的數組:PHP重複數組項基於價值

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

我希望新的數組是這樣的:

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

你真的應該說你已經嘗試過什麼,並要求對如何排序它幫助。 –

回答

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 
+0

請添加一些解釋。這將有助於 –

+0

@SougataBose完成:)謝謝! – Naincy

0

你可以做一個foreach的數組並用於循環使用它的值

步驟1:

不要用鍵值對的foreach循環與數組

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

第2步:

在foreach循環中,它的循環做一個價值

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

第3步:

指定的該$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

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