亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

扁平化多級對象數組的函數

扁平化多級對象數組的函數

PHP
慕標琳琳 2022-10-28 14:52:30
我有一個 stdObjects 數組,它們是多級的。我需要把它們弄平。這是對象數組:[    (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            }        ]    }]現在我創建了以下函數來將多級(可以達到 4 級深)減少到單級并將對象轉換為經典數組: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);它不能正常工作,我只能將第一級放回我的新陣列中。我嘗試了很多關于如何獲得結果的變化,但所有這些都失敗了。當我對所有foreach()循環進行硬編碼時,它可以工作......這是我當前的輸出:[    (int) 0 => [        'link' => '',        'icon' => '',        'title' => 'Main',        'id' => (int) 2    ]]任何人都知道如何解決我的問題?
查看完整描述

1 回答

?
MMTTMM

TA貢獻1869條經驗 獲得超4個贊

我只需要添加&到函數中:

reduceArrayOfObjects(array $array, array &$flatArray, $children = 'children) {}


查看完整回答
反對 回復 2022-10-28
  • 1 回答
  • 0 關注
  • 141 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號