drtzb06222 2012-10-01 16:19
浏览 49
已采纳

如何组合多维数组中的数组并计算值?

I'm a beginner at php and was searching for a solution all day long without success.

I have the following array:

$data = Array
(
[0] => Array
    (
        [my_id] => 1
        [my_post_id] => 123
        [my_status] => 1
        [my_rating] => 5
    )

[1] => Array
    (
        [my_id] => 2
        [my_post_id] => 123
        [my_status] => 1
        [my_rating] => 4
    )

[2] => Array
    (
        [my_id] => 3
        [my_post_id] => 123
        [my_status] => 1
        [my_rating] => 5
    )

[3] => Array
    (
        [my_id] => 4
        [my_post_id] => 456
        [my_status] => 1
        [my_rating] => 5
    )

[4] => Array
    (
        [my_id] => 5
        [my_post_id] => 456
        [my_status] => 1
        [my_rating] => 3
    )
)

and would like to merge the arrays with the same 'my_post_id' and count the values for 'my_status' and 'my_rating' which have the same 'my_post_id'.

At the end, I would like to have the following array:

 $data = Array
(
[0] => Array
    (
        [my_post_id] => 123
        [my_status] => 3
        [my_rating] => 14
    )

[1] => Array
    (
        [my_post_id] => 456
        [my_status] => 2
        [my_rating] => 8
    )
)

I could get arrays with unique 'my_post_id' with the following code but I couldn't find out how to count the other values.

$out = array();
    foreach( $data as $row ) {
        $out[$row['my_post_id']] = $row;
    }
    $array = array_values( $out );

Any help would be much appreciated.

Daniel

  • 写回答

2条回答 默认 最新

  • duanluan2047 2012-10-01 16:38
    关注

    This will produce the array you are looking for:

    $out = array();
    foreach( $data as $row ) {
        if (!isset($out[$row['my_post_id']])) {
            $out[$row['my_post_id']] = Array( "my_id"=>$row['my_id'],
                                              "my_status" => $row["my_status"],
                                              "my_rating" => $row["my_rating"]);
        }
        else {
            $out[$row['my_post_id']]["my_status"] += $row["my_status"];
            $out[$row['my_post_id']]["my_rating"] += $row["my_rating"];
        }
    
    }
    

    results in:

    Array
    (
        [123] => Array
            (
                [my_id] => 1
                [my_status] => 3
                [my_rating] => 14
            )
    
        [456] => Array
            (
                [my_id] => 4
                [my_status] => 2
                [my_rating] => 8
            )
    
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来