John Davidson

Recursion array of categories an subcategories PHP

0 comments
Message:


I have array of categories which has inside many subcategories, each sub categories have their sub categories and so on ...


array(1) {
["categories"]=>array(11) {
[0]=>array(4) {
["id"]=>int(368)
["name"]=>string(8) "Aksesuar"
["parentId"]=>NULL
["subCategories"]=>array(15) {
[0]=>
array(4) {
["id"]=>
int(387)
["name"]=>
string(4) "Saat"
["parentId"]=>
int(368)
["subCategories"]=>
array(0) {
}
}
[1]=>
array(4) {
["id"]=>
int(394)
["name"]=>
string(6) "Şapka"
["parentId"]=>
int(368)
["subCategories"]=>
array(0) {
}
}
[2]=>
array(4) {
["id"]=>
int(396)
["name"]=>
string(17) "Takı & Mücevher"
["parentId"]=>
int(368)
["subCategories"]=>
array(17) {
[0]=>
array(4) {
["id"]=>
int(397)
["name"]=>
string(8) "Bileklik"
["parentId"]=>
int(396)
["subCategories"]=>
array(7) {
[0]=>
array(4) {
["id"]=>
int(1238)
["name"]=>
string(15) "Altın Bileklik"
["parentId"]=>
int(397)
["subCategories"]=>
array(0) {
}
}

Each of this subcategories have parentId which indicates parent category,Most top parent category has parent id null. I need a recursive function which I will give parameters as id of subcategory and array of categories, and it will return array of parent categories with it's respect subcategories.


function recursive($needle, $array, $id, $holder = [])
{
$holder = [];
foreach ($array as $key => $value) {
if ($key == $needle && $value == $id) {
$holder = array_merge($holder, $array);
}
if (is_array($value)) {
$holder = array_merge($holder, recursive($needle, $value, $id, $holder));
}
}

return $holder;
}
$res = recursive('id', $categories, 5208);

Above function just return array of parent category with its sub categories.



My Answer:
To achieve the desired result, you can modify the recursive function as follows:

php
function recursive($needle, $array, $id, $holder = [])
{
foreach ($array as $key => $value) {
if (is_array($value)) {
if (isset($value[$needle]) && $value[$needle] == $id) {
$holder[] = $value;
}
$holder = array_merge($holder, recursive($needle, $value, $id, $holder));
}
}

return $holder;
}

$res = recursive('id', $categories['categories'], 1238);
print_r($res);


In this modified function, we check if the current value is an array and if it has the specified id. If it does, we add it to the holder array. Then, we recursively call the function on the subcategories of the current value. Finally, we return the holder array containing all the parent categories with their respective subcategories.

You can call this function with the 'id' key, the array of categories, and the id of the subcategory you want to find the parent categories for. The function will return an array of parent categories with their subcategories.

Rate this post

3 of 5 based on 2672 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us