初心者質問で申し訳ございませんが、phpの参照渡しについて教えてください。
親子関係のあるデータをもとにツリー構造を作ろうと、いろいろ調べて以下のようなコードを書きました。
参考にしたのはこちらのQiita記事です。
リンク内容
たしかに参照渡しを使うとネスト構造になりますが、正直どういう処理が行われてそうなるのかよく理解できておりません。
公式などドキュメントは読みましたが、わかったようなわからないような…。
以下のコードで参照渡しを使うことで、なぜネストにできるのか、かみ砕いて説明していただけないでしょうか。
親子関係をもつデータの一覧を整形 /* 親子関係の配列を作る * @param array $definitionList * @return array */ private function createNest(array $definitionList): array { $newList = []; foreach ($definitionList as $def) { $newList[$def->getId()] = [ 'id'=>$def->getId(), 'definition'=>$def->getName(), 'parentDataId'=>($def->getParentData() ? $def->getParentmData()->getId() : ''), } $nests = $this->createNestRecursive($newList); return $nests; }
※$definitionListはDBから取得したArrayCollectionで内部に自身のIDと親データを持っています。
//ツリー構造を作る。 private function createNestRecursive(array $newList) { $tree = []; $index = []; foreach ($newList as $id=>$data) { $index[$id] = [ 'id' => $id, 'parent' => $data['parentDataId'], //子を保持するための配列 'children' => [], ]; } foreach ($index as $key=>$value) { if (array_key_exists($value['parentDataId'], $index) && $value['parentDataId'] != $value['id']) { $index[$value['parentDataId']]['children'][] = &$index[$key]; } else { $tree[] = &$index[$key]; } } return $tree; }
回答2件
あなたの回答
tips
プレビュー