1

好吧,这个小问题快把我逼疯了。

这是 $strap_materials 的 print_r 输出:

Array(
    [0] => steel
    [1] => leather
    [2] => polyester
    [3] => leather
    [4] => steel 
)

我想计算每个值存在多少次并将每个总和放入数组中的数组中,就像这样:

Array(
    [0] => Array(
        "name"  => steel
        "count" => 2
    )
    [1] => Array(
        "name"  => leather
        "count" => 2
    )
    [0] => Array(
        "name"  => polyester
        "count" => 1
    )
)

我的意图是像这样使用新创建的数组:

foreach($straps as $strap) {
    echo "Name: " . $strap->name;
    echo "Count: " . $strap->count;
}

我怎样才能做到这一点?

4

1 回答 1

4

您可以使用array_count_values()

$counts = array_count_values($strap_materials);

foreach ($counts as $name => $count) {
    ...
}
于 2013-02-28T21:05:27.217 回答