组匹配的数组值

时间:2013-10-12 03:24:11

标签: php

程序:

while($i<=$row) {
  echo $arr[$i][1].$arr[$i][4]
}

输出

Product Code       Qty
KC_DRINK_TASTY_CASE 1
KC_DRINK_TASTY_CASE 1
KC_DRINK_TASTY_CASE 1
KC_DRINK_TASTY_CASE 1
KC_SUNGLASSES_BK    1
KC_SUNGLASSES_BK    1
KC_SUNGLASSES_BE    1
KC_SUNGLASSES_BE    1
KC_SUNGLASSES_OE    1
KC_SUNGLASSES_OE    1
KC_SUNGLASSES_RD    1
KC_SUNGLASSES_RD    1
KC_SUNGLASSES_WE    1
KC_SUNGLASSES_WE    1

我希望它输出

KC_DRINK_TASTY_CASE 4
KC_SUNGLASSES 10

以便它将产品代码分组,不包括最后一个下划线并将其数量相加

1 个答案:

答案 0 :(得分:0)

如果$arr看起来像这样:

$arr = array(
    array('{something}', 'KC_DRINK_TASTY_CASE', '{something}', '{something}', 1),
    array('{something}', 'KC_SUNGLASSES_BK', '{something}', '{something}', 1),
    // ...
);

然后你可以得到你喜欢的输出:

// we'll store counts here
$result = array();

foreach ($arr as $row) {
    $product = $row[1];
    $qty = $row[4];

    // figure out where the last underscore is and chop off everything that follows it
    // this is VERY brittle. If the product ends up with a name like _SOMEKEY you'll end
    // up with an empty key. Not good. Probably not a huge issue, but buyer beware
    $_product = substr($product, 0, strrpos($product, '_'));

    if (isset($result[$_product])) {
        $result[$_product] += $qty; // we already started counting
    } else {
        $result[$_product] = $qty; // not started counting this product yet, start it
    }
}

// now print your result:
foreach ($result as $id => $qty) {
    echo $id, "\t", $qty, PHP_EOL;
}