我有一個 stdObjects 數(shù)組,它們是多級的。我需要把它們弄平。這是對象數(shù)組:[ (int) 0 => object(stdClass) { link => '' icon => '' title => 'Main' id => (int) 2 children => [ (int) 0 => object(stdClass) { link => 'YTo0OntzOjEwOiJjb250cm9sbGVyIjtzOjU6InBhZ2VzIjtzOjY6ImFjdGlvbiI7czo3OiJkaXNwbGF5IjtzOjU6InBhc3MwIjtzOjQ6ImhvbWUiO3M6NToicGFzczEiO3M6MDoiIjt9' icon => 'fa-tachometer-alt' title => 'Dashboard' id => (int) 3 } ] }]現(xiàn)在我創(chuàng)建了以下函數(shù)來將多級(可以達到 4 級深)減少到單級并將對象轉(zhuǎn)換為經(jīng)典數(shù)組:function reduceArrayOfObjects(array $array, array $flatArray, $children = 'children') { foreach($array as $lvl1) { $lvl1 = (array) $lvl1; if(isset($lvl1[$children])) { reduceArrayOfObjects($lvl1[$children], $flatArray, $children); unset($lvl1[$children]); } $flatArray[] = $lvl1; } return $flatArray;}$multiLevel = []; // this is the array of objects$newArray = [];reduceArrayOfObjects($multiLevel, $newArray);它不能正常工作,我只能將第一級放回我的新陣列中。我嘗試了很多關(guān)于如何獲得結(jié)果的變化,但所有這些都失敗了。當我對所有foreach()循環(huán)進行硬編碼時,它可以工作......這是我當前的輸出:[ (int) 0 => [ 'link' => '', 'icon' => '', 'title' => 'Main', 'id' => (int) 2 ]]任何人都知道如何解決我的問題?
1 回答

MMTTMM
TA貢獻1869條經(jīng)驗 獲得超4個贊
我只需要添加&
到函數(shù)中:
reduceArrayOfObjects(array $array, array &$flatArray, $children = 'children) {}
- 1 回答
- 0 關(guān)注
- 140 瀏覽
添加回答
舉報
0/150
提交
取消