PHP数组合并问题,二维数组合并成三位数组

原数组$result=Array
(
[0] => Array
(
[id] => 5
[activity_id] => 2
[applyid] => 5
[signedtime] => 1463056411
[typeid] => 1
[name] => 王
)

[1] => Array
(
[id] => 6
[activity_id] => 2
[applyid] => 5
[signedtime] => 1463066411
[typeid] => 2
[name] => 王
)

[2] => Array
(
[id] => 8
[activity_id] => 2
[applyid] => 5
[signedtime] => 1463066411
[typeid] => 4
[name] => 王
)

[3] => Array
(
[id] => 9
[activity_id] => 2
[applyid] => 6
[signedtime] => 1463066411
[typeid] => 4
[name] => zhang
)

)
合并后要求成为这样:
$result=Array
(
[0] => Array
(
[id] => 5
[activity_id] => 2
[applyid] => 5
[signed]=>array(
[0]=>array(
[signedtime] => 1463056411
[typeid] => 1
)
[1]=>array(
[signedtime] => 1463066411
[typeid] => 2
)
[2]=>array(
[signedtime] => 1463066411
[typeid] => 4
)

)
[name] => 王
)

[1] => Array
(
[id] => 9
[activity_id] => 2
[applyid] => 6
[signed]=>array(
[0]=>array(
[signedtime] => 1463066411
[typeid] => 4
)

)
[name] => zhang
)

)
最新回答
⊿半季离殇

2025-03-30 20:43:20

<?php
$result=array(
    array
        (
            "id" => 5,
            "activity_id" => 2,
            "applyid" => 5,
            "signedtime" => 1463056411,
            "typeid" => 1,
            "name" => '王',
        ),
    array
        (
            "id" => 6,
            "activity_id" => 2,
            "applyid" => 5,
            "signedtime" => 1463066411,
            "typeid" => 2,
            "name" => '王',
        ),
    array
        (
            "id" => 8,
            "activity_id" => 2,
            "applyid" => 5,
            "signedtime" => 1463066411,
            "typeid" => 4,
            "name" => '王',
        ),
    array
        (
            "id" => 9,
            "activity_id" => 2,
            "applyid" => 6,
            "signedtime" => 1463066411,
            "typeid" => 4,
            "name" => 'zhang',
        )
);

//print_r($result);


$new_rst = array();
$keys    = array();
foreach($result as $arr){
    $_arr  = $arr;
    unset($_arr["signedtime"], $_arr["typeid"]);
    $vals1  = $_arr;

    unset($_arr["id"]);
    $key = implode('-', $_arr);
    if(isset($keys[$key])){
        $_arr = $new_rst[$key];
        $_arr['signed'][] = array($arr["signedtime"], $arr["typeid"]);
        $new_rst[$key] = $_arr;
    } else {
        $_arr['signed'][] = array($arr["signedtime"], $arr["typeid"]);
        $new_rst[$key] = $_arr;
        $keys[$key] = true;
    }
    
}
$new_rst = array_values($new_rst);
print_r($new_rst);

exit;
追问
要把applyid相同的合并成一个数组。。
追答
$key = implode('-', $_arr);
改为
$key = $_arr['applyid'];
不要忘記

2025-03-30 22:17:35

foreach($result as $k => $v){
    $result[$k]['signed'] = array('signedtime'=>$result[$k]['signedtime'],'typeid'=>$result[$k]['typeid']);
    unset($result[$k]['signedtime']);
    unset($result[$k]['typeid']);
}
追问
不是这样的  要把[applyid]相同的合并成一个