要麼我是盲人,要麼我在這裏的任何地方都找不到這個問題。 昨天我遇到了合併陣列的問題,我可以在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
)
)
我試過幾個合併功能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;
}
而結果正是我想要的!
使用'array_merge_recursive' - http://php.net/manual/en/function.array-merge-recursive.php – maximkou
我做到了,但結果是一樣的。 'lang'覆蓋'groups' –
如果你有和數組,試試這個'$ resultArray = $ usergroup ['groups'] + $ usergroup ['lang']' – maximkou