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

时间:2016-12-10 09:48:47

标签: php arrays multidimensional-array

我有一个类似

的数组
    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
        )

)

我想使用'id'合并这些数组,输出应该像

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

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

)

还想合并用逗号分隔的resource_id

2 个答案:

答案 0 :(得分:0)

我认为这可以帮助你做出你需要的东西

<?php
    $myArray = [
      ["id"=>1,"value"=>10],
      ["id"=>1,"value"=>20],
      ["id"=>1,"value"=>30],
      ["id"=>2,"value"=>40],
      ["id"=>2,"value"=>50]
    ];


    $sumArray = array();

    foreach ($myArray as $k=>$value) {
      $sumArray[$value['id']] .= ($sumArray[$value['id']]) ? ", ":""; 
      $sumArray[$value['id']] .= $value['value'];
    }

    print_r($sumArray);
?>

在这里玩:https://eval.in/694544

如果您尝试了但仍未解决问题,请点击此处:https://eval.in/694562

答案 1 :(得分:0)

尝试一下,这就是你的问题(按照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);
?>