好吧,这个小问题让我疯了。
这是$ 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;
}
我怎样才能做到这一点?
答案 0 :(得分:4)
您可以使用array_count_values()
:
$counts = array_count_values($strap_materials);
foreach ($counts as $name => $count) {
...
}