Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

php数组合并的问题

今天项目遇到一个分类合并的问题结构如下;

$a= [
    0=>[
     'id' =>1,
     'name'=>'技术部',
     'job'=>'后台开发'
    ],
    1=>[
     'id' =>1,
     'name'=>'技术部',
     'job'=>'前端开发'
    ],
    2=>[
     'id' =>2,
     'name'=>'设计部',
     'job'=>'UI设计师'
    ],
    3=>[
     'id' =>1,
     'name'=>'技术部',
     'job'=>'前端开发444'
    ],
];

现在就是想要的结构就是这样的效果:

Array
(
    [0] => Array
        (
            [name] => 技术部
            [job] => Array
                (
                    [0] => 后台开发
                    [1] => 前端开发
                    [2] => 前端开发444
                )

        )
    [1] => Array
        (
            [name] => 设计部
            [job] => Array
                (
                    [0] => UI设计师
                )

        )

)

我一开始想,想把id相同的丢到一个数组中,然后在循环这个数组,取到name和job。但是发现一个问题就是,foreach用的很多,感觉方法不是好。。所以请问下大家, 有什么好的方法或者思路。

下面的我改的代码

$res = [];
foreach ($a as $k => $v) {
    $res[$v['id']][] = $v;
}

foreach ($res as $key => $value) {
   foreach ($value as $k2 => $v2) {
      $res2[] = [
          'name' =>$v2['name'],
          'job' => array_column($value,'job')
      ];

   }
}

print_r($res2);

下面的代码实际出来的效果。会有重复。。,所以最后一步还要去去重。。很麻烦


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

$a= [

0=>[
 'id' =>1,
 'name'=>'技术部',
 'job'=>'后台开发'
],
1=>[
 'id' =>1,
 'name'=>'技术部',
 'job'=>'前端开发'
],
2=>[
 'id' =>2,
 'name'=>'设计部',
 'job'=>'UI设计师'
],
3=>[
 'id' =>1,
 'name'=>'技术部',
 'job'=>'前端开发444'
],

];

$result = array();

foreach ($a as $key => $val) {

$result[$val['id']]['name']   = $val['name'];
$result[$val['id']]['job'][]  = $val['job'];

}

$result = array_values($result);

var_dump($result);die;

如果说你要去重就用isset去判断下


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...