php – 多维数组上的数组合并

前端之家收集整理的这篇文章主要介绍了php – 多维数组上的数组合并前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
无论是我是盲人还是我无法在这里找到这个问题.
昨天我遇到了合并数组的问题,我可以在SO的帮助下解决这个问题.今天我再次遇到了合并数组的问题,但这次是使用多维数组.

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

$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
        )

)

并且$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
        )

)

我希望我的合并数组看起来像这样:

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?

我已经尝试了PHP的几个合并函数(array_merge()和array_merge_recursive()),我得到的最接近的结果是,第二个数组([‘lang’])覆盖了第一个数组([‘groups’]).为了解决这个问题,我尝试删除lang数组上的空值(始终为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);
}

返回命令上的array_merge()似乎根本没有做任何事情,所以我可能没有正确地收集数据或者我用数组搞乱了一些东西(忘记添加[],或者我不知道. ..).我有点想念这里的树林.

我可以去哪个方向的建议?

编辑:使用PédeLeã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;
}

结果正是我想要的!

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

猜你在找的PHP相关文章