2016-04-05 93 views
2

鑑於數組是這樣的:更新價值

$products = array([0] => Apple, [1] => Orange, [2] => Orange, [3] => Strawberry, [4] => Orange, [5] => Mango, [6] => Orange, [7] => Strawberry, [8] => Orange, [9] => Orange, [10] => Orange); 

我需要計算類似值的數量和接收陣列,其中每個獨特的價值會隨着計數一起出現一次它從原始數組中出現。 例如新的數組應該是這樣的:

$new_products = array([0] => "Apple 1", [1] => "Orange 7", [2] => "Strawberry 2", [3] => "Mango 1"); 

使用功能下我可以收到2個陣列:

array_keys(array_count_values($products))); // Return array of unique values 
array_values(array_count_values($products))); // Return array with count for each unique values 

返回結果:

Array ([0] => Apple 1 [1] => Orange [2] => Strawberry [3] => Mango) 
Array ([0] => 1 [1] => 7 [2] => 2 [3] => 1) 

我不能找到一種方法,合併這些值,以便在我的示例中獲得類似$ new_products數組的數組。

+2

$結果= array_map(函數($ I1,$ 3-12){返回$ I1 ''。 $ i2;},$ ar_keys,$ ar_counts); – splash58

+1

嗨,@Uchiha!百年還沒有見過:) – splash58

+0

@Uchiha,有時用我的母語閱讀太好了:) – splash58

回答

5

剛剛迭代array_count_valuesforeach

$new_products = []; 
foreach (array_count_values($products) as $name => $count) { 
    $new_products[] = $name. ' '. $count; 
} 
+0

謝謝!像魅力一樣工作! – Sergio

2

嘗試此功能:

<?php 

$products = array(
    0 => 'Apple', 
    1 => 'Orange', 
    2 => 'Orange', 
    3 => 'Strawberry', 
    4 => 'Orange', 
    5 => 'Mango', 
    6 => 'Orange', 
    7 => 'Strawberry', 
    8 => 'Orange', 
    9 => 'Orange', 
    10 => 'Orange' 
); 

function getNamesWithCountArray($array) 
{ 
    $result = array(); 
    $countedValues = array_count_values($array); 

    foreach($countedValues as $key => $value) 
     $result[] = $key . ' ' . $value; 

    return $result; 
} 

$new_products = getNamesWithCountArray($products); 

echo '<pre>'; 
print_r($new_products); 

print_r($new_products);結果是:

Array 
(
    [0] => Apple 1 
    [1] => Orange 7 
    [2] => Strawberry 2 
    [3] => Mango 1 
)