仅在数组中显示项目及其数量之和

时间:2015-01-29 09:39:48

标签: php arrays sorting

我有一个看起来像这样的数组:

Array
(
    [0] => Jenni
    [1] => 1
    [2] => Silver
    [3] => 1
    [4] => Jenni
    [5] => 1
    [6] => Silver
    [7] => 1
    [8] => Jenni
    [9] => 1
    [16] => Jenni
    [17] => 1
    [18] => Silver
    [19] => 1
    [20] => Calavera
    [21] => 1
    [22] => Jenni
    [23] => 2
    [24] => Silver
    [25] => 1
)

第一个是名称,第二个是数量。现在我想只显示每个名称及其数量之和.Eg Jenni - >数量5。 我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

//$data is your array
$result = array();
$key = '';
foreach ($data as $index => $value) {
    //use every even index as key
    if ($index % 2 == 0) {
        $key = $value;
    } else {
      //set or alter the value
      if (isset($result[$key])) {
          $result[$key] += $value;
      } else {
          $result[$key] = $value;
      }
    }
}

之后,您可以显示所有这些值:

foreach ($result as $name => $quantity) {
    echo $name . ' -> Quantity ' . $quantity . "\n";//or '<br />' instead of "\n"
}

答案 1 :(得分:0)

您的数组键未排序,如果要对其执行求和,则数组键必须按顺序排列。

Eg:

    $array_holder = array("Jenni","1","Silver","1","Jenni","1","Silver","1","Jenni","1","Jenni","1","Silver","1","Calavera","1","Jenni","2","Silver","1");

    //This is optional if your array is sorted
    $array_holder = array_values($array_holder);//Return sort keys


    $total = count($array_holder);
    $sum = array();
    for($i = 0 < $i < $total; $i+2){
            $sum[$array_holder[$i]] = isset($sum[$array_holder[$i]]) ? $sum[$array_holder[$i]] + $array_holder[$i+1] : $array_holder[$i+1];
   }