php 多维数组上的数组合并

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17850353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:34:04  来源:igfitidea点击:

Array merge on multidimensional array

phparraysmultidimensional-array

提问by Patrick Manser

Either I'm blind or I can't find this problem anywhere here on SO. Yesterday I had a problem with merging arrays, which I could fix with the help of SO. Today I have, again, a problem with merging arrays, but this time it's with multidimensional Arrays.

要么我瞎了,要么我在 SO 上的任何地方都找不到这个问题。昨天我在合并数组时遇到了问题,我可以在 SO 的帮助下解决这个问题。今天我再次遇到合并数组的问题,但这次是多维数组。

I have an array $usergroup['groups']and an array $usergroup['lang']

我有一个数组$usergroup['groups']和一个数组$usergroup['lang']

$usergroup['groups']looks like this:

$usergroup['groups']看起来像这样:

Array
(
    [0] => Usergroup_Model Object
        (
            [id] => 1
            [deleted] => 0
        )

    [1] => Usergroup_Model Object
        (
            [id] => 2
            [deleted] => 0
        )

    [2] => Usergroup_Model Object
        (
            [id] => 3
            [deleted] => 0
        )

)

And $usergroup['lang']looks like this:

而且$usergroup['lang']是这样的:

Array
(
    [0] => Usergroup_Model Object
        (
            [id] => 
            [id_usergroup] => 1
            [name] => Administratoren
            [id_lang] => 1
        )

    [1] => Usergroup_Model Object
        (
            [id] => 
            [id_usergroup] => 2
            [name] => Benutzer
            [id_lang] => 1
        )

    [2] => Usergroup_Model Object
        (
            [id] => 
            [id_usergroup] => 3
            [name] => G?ste
            [id_lang] => 1
        )

)

I want my merged array to look like this:

我希望我的合并数组如下所示:

Array
(
    [0] => Usergroup_Model Object
        (
            [id] => 1
            [id_usergroup] => 1
            [name] => Administratoren
            [id_lang] => 1
            [deleted] => 0
        )

    [1] => Usergroup_Model Object
        (
            [id] => 2
            [id_usergroup] => 2
            [name] => Benutzer
            [id_lang] => 1
            [deleted] => 0
        )

    [2] => Usergroup_Model Object
        (
            [id] => 3
            [id_usergroup] => 3
            [name] => G?ste
            [id_lang] => 1
            [deleted] => 0
        )

)

What have I tried?

我尝试了什么?

I've tried several merging functions (array_merge()and array_merge_recursive()) of PHP, the closest result I got was, that the second Array (['lang']) overwrote the first Array (['groups']). To fix that, I tried to remove the empty values on the langArray (which is always id). But that does not fix it. The code - at the moment - looks like this:

我已经尝试了PHP 的几个合并函数(array_merge()array_merge_recursive()),我得到的最接近的结果是,第二个数组(['lang'])覆盖了第一个数组(['groups'])。为了解决这个问题,我尝试删除langArray上的空值(始终为id)。但这并不能解决问题。代码 - 目前 - 看起来像这样:

public static function getAll()
{
  $usergroup['groups'] = self::find();
  $usergroup['lang'] = self::findInTable(array(
    'id_lang' => Language_Model::getDefaultLanguage()
  ), self::dbTranslationTable);
  foreach ($usergroup as $ug) {
    $ug = array_filter($ug, function($val) {
      return $val != '';
    });
  }
  return array_merge($ug);
}

The array_merge() on the return command doesn't seem to do anything at all, so I'm probably not gathering the data correctly or I mess something up with the Arrays (forgetting to add [], or I don't know...). I kinda miss the forest for the trees here.

return 命令中的 array_merge() 似乎根本没有做任何事情,所以我可能没有正确收集数据,或者我把数组搞砸了(忘记添加 [],或者我不知道。 ...)。我有点想念这里的树林。

Any suggestions in which direction I could go?

有什么建议可以朝哪个方向发展?

Edit:With the code provided by Pé de Le?o I was able to solve the problem. My function now looks like this:

编辑:使用 Pé de Le?o 提供的代码,我能够解决问题。我的函数现在看起来像这样:

public static function getAll()
{
  $usergroup['groups'] = self::find();
  $usergroup['lang'] = self::findInTable(array(
    'id_lang' => Language_Model::getDefaultLanguage()
  ), self::dbTranslationTable);
  $out = array();
  foreach ($usergroup['groups'] as $key => $value) {
    $out[] = (object) array_merge((array) $usergroup['lang'][$key], (array) $value);
  }
  return $out;
}

And the result is exactly how I wanted it!

结果正是我想要的!

回答by Expedito

$out = array();
foreach ($arr1 as $key => $value){
    $out[] = (object)array_merge((array)$arr2[$key], (array)$value);
}
print_r($out)

回答by steven

maybe its not the smartest but you can try it like this, too:

也许它不是最聪明的,但你也可以这样尝试:

public static function getAll()
{
  $groups = self::find();
  $lang = self::findInTable(array(
    'id_lang' => Language_Model::getDefaultLanguage()
  ), self::dbTranslationTable);

  $n = array();
  foreach($groups as $g) {
      $id = $g['id'];
      $n[$id] = $g;
  }

  foreach($lang as $a) {
      $id = $a['id_usergroup'];
      if(!isset($n[$id])){ $n[$id] = array(); }
      $n[$id]['id_usergroup'] = $a['id_usergroup'];
      $n[$id]['name'] = $a['name'];
      $n[$id]['id_lang'] = $a['id_lang'];
  }

  return $n;
}

the key of the returned array will be the id of the group in this example.

在此示例中,返回数组的键将是组的 id。

回答by Owen Beresford

I have never array_merge() with objects before. I suspect you would need to have classes like UNION for it to work (i.e. public data).

我以前从未使用过 array_merge() 对象。我怀疑你需要有像 UNION 这样的类才能工作(即公共数据)。

  • Assertion: this is your data structure and it won't change much.
  • Assertion: if you had provided var_export() output rather than print_r() in the samples at the top, I could have executed the following (to test it)...
  • It would be better to use a more specific class in the last used cast statement, but I don't know your class hierarchy ~ Usergroup_Model?
  • This answer ignore anything to do with getDefaultLanguage() as that wasn't part of the question.

    $ITEMS=count($usergroup['groups']);
    $out=array();
    for($i=0; $i<$ITEMS; $i++) {
        if(isset($usergroup['lang'][$i])) {
            $out[]=(object)array_merge((array)$usergroup['groups'][$i], (array)$usergroup['lang'][$i]);
        } else {
            $out[]=$usergroup['groups'][$i];
        }
    }
    
  • 断言:这是您的数据结构,不会有太大变化。
  • 断言:如果您在顶部的示例中提供了 var_export() 输出而不是 print_r() ,我可以执行以下操作(以对其进行测试)...
  • 在上次使用的cast语句中使用更具体的类会更好,但我不知道你的类层次结构~Usergroup_Model?
  • 这个答案忽略了与 getDefaultLanguage() 相关的任何事情,因为那不是问题的一部分。

    $ITEMS=count($usergroup['groups']);
    $out=array();
    for($i=0; $i<$ITEMS; $i++) {
        if(isset($usergroup['lang'][$i])) {
            $out[]=(object)array_merge((array)$usergroup['groups'][$i], (array)$usergroup['lang'][$i]);
        } else {
            $out[]=$usergroup['groups'][$i];
        }
    }
    

回答by Vinod Joshi

if(count($array1) >= count($array2)){
    $arr1 = $array1;
    $arr2 = $array2;
}else{
    $arr1 = $array2;
    $arr2 = $array1;
}

$out = array();
foreach ($arr1 as $key => $value){
    if(isset($arr2[$key])){
        $out[] = array_merge((array)$arr2[$key], (array)$value);
    }else{
        $out[] = (array)$value;
    }
}

pr($out);