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条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?