duanbaque4230 2017-08-02 13:02
浏览 44
已采纳

将数组中的类似值分组

Here is the array, which I have posted through Ajax and get into the ajax.php file. Now i want to add a new array, as shown below.

Array
(
    [0] => Array
        (
            [contact_id] => 5000
            [invoice] => 476
        )

    [1] => Array
        (
            [contact_id] => 5000
            [invoice] => 396
        )

    [2] => Array
        (
            [contact_id] => 1490
            [invoice] => 1083
        )

    [3] => Array
        (
            [contact_id] => 1490
            [invoice] => 498


  )
)

I also want to add this if contact id are same, then invoice will be added

Array
(
    [0] => Array
        (
            [contact_id] => 5000
            [invoice] => Array (
                    [0] =>476,
                    [1] =>396
            )
        )

    [2] => Array
        (
            [contact_id] => 1490
            [invoice] => Array (
                    [0] =>1083,
                    [1] =>498
            )
        )
)

I tried to do it, without success. Here is my code:

$invtemp =array();
 foreach($_POST['invoice_id'] as $value){
    if(!in_array($value['contact_id'], $invtemp, true)){
         $arr = array($value['contact_id'] => $value['invoice'] );
         array_push($invtemp, $arr);    
    }
}
  • 写回答

3条回答 默认 最新

  • drbe16008 2017-08-02 13:10
    关注

    I think you can achieve with simple foreach:

    foreach ($array as $value) {
        $arr[$value['contact_id']]['contact_id'] = $value['contact_id'];
        $arr[$value['contact_id']]['invoice'][] = $value['invoice'];
    }
    
    print_r($arr);
    

    This provides:

    Array
    (
        [5000] => Array
            (
                [contact_id] => 5000
                [invoice] => Array
                    (
                        [0] => 476
                        [1] => 396
                    )
    
            )
    
        [1490] => Array
            (
                [contact_id] => 1490
                [invoice] => Array
                    (
                        [0] => 1083
                        [1] => 498
                    )
    
            )
    
    )
    

    To reset the keys:

    print_r(array_values($arr));
    

    Not so important, but to make it cleaner, you can use extract:

    foreach ($array as $value) {
        extract($value);
        $arr[$contact_id]['contact_id'] = $contact_id;
        $arr[$contact_id]['invoice'][] = $invoice;
    }
    
    print_r($arr);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

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