3v4l.org

run code in 500+ PHP versions simultaneously
<?php $arr = ["categories" => [ [ 'id' => 368, 'name' => 'Aksesuar', 'parentId' => NULL, 'subCategories' => [ [ 'id' => 387, 'name' => 'Saat', 'parentId' => 368, 'subCategories' => [] ], [ 'id' => 394, 'name' => 'Şapka', 'parentId' => 368, 'subCategories' => [] ], [ 'id' => 396, 'name' => 'Takı & Mücevher', 'parentId' => 368, 'subCategories' => [ [ 'id' => 397, 'name' => 'Bileklik', 'parentId' => 396, 'subCategories' => [ [ 'id' => 1238, 'name' => 'Altın Bileklik', 'parentId' => 397, 'subCategories' => [] ] ] ] ] ], ] ] ]]; function recursive(string $needle, array $categories, $id): ?array { foreach ($categories as $cat) { if (array_key_exists($needle, $cat) && $cat[$needle] === $id) { // make sure that if correct category is found, // no subcategories will be included unset($cat['subCategories']); return $cat; } else { $subCat = recursive($needle, $cat['subCategories'], $id); // if the $subCat is not null, it indicates the category // with the correct id, or one of it's parent has been found if ($subCat !== null) { $cat['subCategories'] = $subCat; return $cat; } } } return null; } var_dump(recursive('id', $arr['categories'], 397));

preferences:
104.58 ms | 1479 KiB | 5 Q