PHP:在多维数组中找到相同的键并合并结果 [英] PHP: find same keys in a multidimensional-array and merge the findings

查看:44
本文介绍了PHP:在多维数组中找到相同的键并合并结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多维数组,如下所示:

I have a multidimensional-array which looks like this:

$array = (
    [0] => array (
        ['WS'] => array(
             [id] => 2,
             [name] => 'hello'
             )
        )
    ), 
    [1] => array (
        ['SS'] => array(
             [id] => 1,
             [name] => 'hello2'
             )
        )
    ),
    [2] => array (
        ['WS'] => array(
             [id] => 5,
             [name] => 'helloAGAIN'
             )
        )
)

如您所见,$array[0] 和 $array[2] 具有相同的键 [WS].我需要一个函数来找到那些相同的键".之后我会将这两个数组合并为一个.例如

As you can see, $array[0] and $array[2] have the same key [WS]. I need a function to find those "same keys". Afterthat I would merge these two arrays into one. f.e.

$array =
(
    [0] => array 
        (
            ['WS'] => array
                (
                     [0] => array
                         (
                             [id] => 2,
                             [name] => 'hello'
                         ),
                     [1] => array
                         (
                            [id] => 5,
                            [name] => 'helloAGAIN'
                         )
                )
        ),
    [1] => array 
         (
             ['SS'] => array
                 (
                     [0] => array
                         (
                              [id] => 1,
                              [name] => 'hello2'
                         )
                 )
         )
    )

希望你们能理解我的问题.问候

Hope you guys understand my problem. greets

推荐答案

function group_by_key ($array) {
  $result = array();
  foreach ($array as $sub) {
    foreach ($sub as $k => $v) {
      $result[$k][] = $v;
    }
  }
  return $result;
}

看看它是否有效

这篇关于PHP:在多维数组中找到相同的键并合并结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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