合并阵列(PHP) [英] Merge arrays (PHP)

查看:144
本文介绍了合并阵列(PHP)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何以这种方式结合的阵列?

How combine arrays in this way?

来源:

Array
(
   [0] => Array
       (
           [id] => 3
           [title] => book
           [tval] => 10000
       )
   [1] => Array
       (
           [id] => 3
           [title] => book
           [tval] => 1700
       )
   [3] => Array
       (
           [id] => 27
           [title] => fruit
           [tval] => 3000
       )

.......

)

结果:

Array
(
   [0] => Array
       (
           [id] => 3
           [title] => book
           [tval] => 10000,1700
       )
   [1] => Array
       (
           [id] => 27
           [title] => fruit
           [tval] => 3000
       )
.......

) 

请帮忙解决这个问题,
谢谢!!!
遗憾的英语不好(

please help to solve this problem, thanks!!! sorry for bad english(

推荐答案

这应该工作:

$result = array();
foreach($array as $elem) {
    $key = $elem['id'];
    if (isset($result[$key])) {
        $result[$key]['tval'] .= ',' . $elem['tval'];
    } else {
        $result[$key] = $elem;
    }
}

这基本上是由 ID ,串联 tvals (由分离,)。

This basically groups elements by id, concatenating tvals (separated by ,).

这篇关于合并阵列(PHP)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆