使用另一个数组中相同索引的值更新数组中的值

时间:2016-04-05 12:28:17

标签: php arrays

给出这样的数组:

$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 个答案:

答案 0 :(得分:5)

只需使用array_count_values重复foreach

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

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