doudao7511 2017-01-17 02:51
浏览 60

如果某些键相似,则合并数组中的数据

Array (
        [0] => Array (
            [Name] => Banana
            [Percentage] => 25
            [Sum] => 70
        )
        [1] => Array (
            [Name] => Banana
            [Percentage] => 25
            [Sum] => 168
        )
        [2] => Array (
            [Name] => Apple
            [Percentage] => 14
            [Sum] => 8
        )
    )

How can I merge the value only if keys [Name] and [Percentage] is similar to the other one in the array ?

For example, I search to have something like this:

Array (
    [0] => Array (
        [Name] => Banana
        [Percentage] => 25
        [Sum] => 238
    )
    [1] => Array (
        [Name] => Apple
        [Percentage] => 14
        [Sum] => 8
    )
)

Here's what I tried:

foreach($myArray as $value){
    $Name = $value['Name'];
    if(isset($result[$Name]))
        $index = count($result[$Name]);
    else
        $index = 1;

    $result['Name'] = $Name;
    $result['Percentage'] = $value['Percentage'];
    $result['Sum'] += $value['Sum'];        
}
$result = array_values($result);

Thanks.

  • 写回答

2条回答 默认 最新

  • dongshao9106 2017-01-17 04:43
    关注

    The problem with what you currently have is that you are just kind of duplicating what you already have in your original array except you are throwing in a failed sum with $result['Sum'] += $value['Sum'];. See new example with notations below:

    # Try setting a storing array
    $new    =   array();
    #loop through the array
    foreach($array as $row) {
        # Check if you have already set the sum for this name type
        if(isset($new[$row['Name']]['Sum']))
            # Add new and stored value together
            $sum    =   $new[$row['Name']]['Sum'] + $row['Sum'];
        else
            # If not already set, set it
            $sum    =   $row['Sum'];
        # Start storing values into the new array. It's easiest to set the key
        # as the name value so it saves to unique keys
        $new[$row['Name']]  =   array(
            'Name'=>$row['Name'],
            'Percentage'=>$row['Percentage'],
            'Sum'=>$sum
        );
    }
    
    print_r(array_values($new));
    
    评论

报告相同问题?

悬赏问题

  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害