简体   繁体   English

基于一个共同的关键PHP合并许多数组

[英]merge many array based on a common key php

I wasn't so clear in my first question, so i deleted it and here is a reformulation; 我的第一个问题不太清楚,因此我删除了它,这是重新编写的; I have those arrays: 我有那些数组:

    $open = array(array("FAI1","34"),array("FAI2","34"),array("FAI3","34"));
    $click = array(array("FAI2","52"),array("FAI1","68"),array("FAI3","99"));
    $unsubscribe = array(array("FAI2","103"),array("FAI3","67"),array("FAI1","102"));
    $def_sent = array(array("FAI1","34",24),array("FAI2","34",23),array("FAI3","34",27));
    $SB = array(array("FAI2","103"),array("FAI3","67"),array("FAI1","102"));
    $HB = array(array("FAI2","103"),array("FAI3","67"),array("FAI1","102"));

I searched for a function to merge them and get a result like this: 我搜索了一个合并它们的函数,并得到如下结果:

     $result = array(array("FAI1",34,68,102,34,24,102,102) 
     ,array("FAI2","34",23.....),
     array("FAI3","34",27....));

and to do this, i used the function, in the php online documentation, and this is the function 为此,我在php在线文档中使用了该功能,这就是该功能

function array_merge_recursive() {

    $arrays = func_get_args();
    $base = array_shift($arrays);

    foreach ($arrays as $array) {
        reset($base); 
        while (list($key, $value) = @each($array)) {
            if (is_array($value) && @is_array($base[$key])) {
                $base[$key] = array_merge_recursive($base[$key], $value);
            } else {
                $base[$key] = $value;
            }
        }
    }

    return $base;
}

But instead of getting the result above i got this: 但是我没有得到上面的结果:

FAI1|34
FAI2|34
FAI3|34
FAI2|52
FAI1|68
FAI3|99
...

So i need some help to reformulate this function to get the expected result. 因此,我需要一些帮助来重新构造此功能以获得预期的结果。

Try this function: 试试这个功能:

function array_merge_rec() {
    $arrays = func_get_args();
    $result = array();
    foreach ($arrays as $arg) {
        if (is_array($arg)) {
            foreach ($arg as $item) {
                if (!isset($result[$item[0]])) {
                    $result[$item[0]] = $item;
                } else {
                    $result[$item[0]][] = $item[1];
                }
            }
        } else {
            echo "$arg skippend because it isn't array\n";
        }
   }

   return array_values($result);

} }

Does it help? 有帮助吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM