doutidi5037 2013-02-28 21:01
浏览 43
已采纳

计算数组中的值[重复]

This question already has an answer here:

Okay, this small problem is driving me insane.

This is the print_r output of $strap_materials:

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

I want to count how many times each value exists and put each sum in an array within an array, just like this:

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

My intention is to use the newly created array like this:

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

How can I achieve that?

</div>
  • 写回答

1条回答 默认 最新

  • doutangliang7769 2013-02-28 21:05
    关注

    You can use array_count_values():

    $counts = array_count_values($strap_materials);
    
    foreach ($counts as $name => $count) {
        ...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 AI大模型精调(百度千帆、飞浆)
  • ¥15 关于#c语言#的问题:我在vscode和codeblocks中编写c语言时出现打不开源文件该怎么办
  • ¥15 非科班怎么跑代码?如何导数据和调参
  • ¥15 福州市的全人群死因监测点死亡原因报表
  • ¥15 Altair EDEM中生成一个颗粒,并且各个方向没有初始速度
  • ¥15 系统2008r2 装机配置推荐一下
  • ¥500 服务器搭建cisco AnyConnect vpn
  • ¥15 悬赏Python-playwright部署在centos7上
  • ¥15 psoc creator软件有没有人能远程安装啊
  • ¥15 快速扫描算法求解Eikonal方程咨询