Обработка массива под родительскую-дочернюю структуру - PHP Online
Form of PHP Sandbox
Enter Your PHP code here for testing/debugging in the Online PHP Sandbox. As in the usual PHP files, you can also add HTML, but do not forget to add the tag <?php
in the places where the PHP script should be executed.
Result of php executing
Full code of Обработка массива под родительскую-дочернюю структуру.php
- <?php
- /**
- * Обработка массива под родительскую/дочернюю структуру
- */
- function recursiveStructureProcessing($collectionArray, $parentId = 0): array
- {
- $collectionResult = [];
- foreach ($collectionArray as $item) {
- if ($item['parent_id'] === $parentId) {
- $item['children'] = recursiveStructureProcessing($collectionArray, $item['id']);
- $collectionResult[] = $item;
- }
- }
- return $collectionResult;
- }
- $originArray = [
- [
- 'id' => 1,
- 'parent_id' => 0,
- 'name' => 'root'
- ],
- [
- 'id' => 2,
- 'parent_id' => 1,
- 'name' => 'folder1'
- ],
- [
- 'id' => 3,
- 'parent_id' => 1,
- 'name' => 'folder2'
- ],
- [
- 'id' => 4,
- 'parent_id' => 2,
- 'name' => 'folder3'
- ],
- [
- 'id' => 5,
- 'parent_id' => 3,
- 'name' => 'folder4'
- ],
- [
- 'id' => 6,
- 'parent_id' => 3,
- 'name' => 'folder5'
- ],
- [
- 'id' => 7,
- 'parent_id' => 5,
- 'name' => 'folder6'
- ],
- [
- 'id' => 8,
- 'parent_id' => 3,
- 'name' => 'folder7'
- ],
- [
- 'id' => 9,
- 'parent_id' => 8,
- 'name' => 'folder8'
- ],
- ];
- var_export(recursiveStructureProcessing($originArray));
File Description
- Обработка массива под родительскую-дочернюю структуру
- PHP Code
- 31 May-2023
- 1.39 Kb
You can Share it:
Latest PHP Pastes