dongzhuanlei0768
2016-12-10 09:48
浏览 53
已采纳

使用相同的id合并多维数组中的数组

I have an array like

    Array
(
    [0] => Array
        (
            [id] => 24
            [resource_id] => 34
        )

    [1] => Array
        (
            [id] => 24
            [resource_id] => 1
        )

    [2] => Array
        (
            [id] => 25
            [resource_id] => 2
        )

    [3] => Array
        (
            [id] => 25
            [resource_id] => 34
        )

)

I want to merge these arrays using 'id' and output should be like

Array
(
    [0] => Array
        (
            [id] => 24
            [resource_id] => 34,1
        )

    [1] => Array
        (
            [id] => 25
            [resource_id] => 2,34
        )

)

Also want to merge resource_id separated with commas.

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dougou8552 2016-12-10 10:19
    已采纳

    Try it , this do your question (Ever the first array sorted by id):

    <?php  
        $arrayToMerge = array(0=>array("id"=>24,"resource_id"=>34) , 1=>array("id"=>24,"resource_id"=>1) , 2=>array("id"=>25,"resource_id"=>2) , 3=>array("id"=>25,"resource_id"=>34));    
        $tmpArray;
        $lastID = "";
        $ids = "";
        $count = 0;
        foreach ($arrayToMerge as $key => $value) {
            $lastID = $value['id'];
            if (empty($ids)) {
                $ids = $lastID;
                $tmpArray = array();
                array_push($tmpArray,array("id"=>$ids,"resource_id"=>$value['resource_id']));
            } else if (strcmp($lastID,$ids)==0){
                $tmpValue = $tmpArray[$count]['resource_id'];
                $tmpArray[$count]['resource_id'] = $tmpValue.','.$value['resource_id'];
            } else {
                $ids = $lastID;
                array_push($tmpArray,array("id"=>$ids,"resource_id"=>$value['resource_id']));
                $count++;
            }
        }
        var_dump($tmpArray);
    ?>
    
    评论
    解决 无用
    打赏 举报
  • 查看更多回答(1条)

相关推荐 更多相似问题