0
votes

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.

Could you please clarify your required outcome a bit more. Let's take the data you've provided. If you call 'recursive('id', $categories, 397)', do you expect the entire tree from the root to the found element (so 368->396->397)? Do the subcategories of the found category (1238) need to be returned as well?vixducis
@vixducis When you pass 397 you will get this category and its sub categories only, what i need is to get whole tree including 397 parent categories. For example when I pass lowest sub category I neeed to get all its parent category, if is lowest in above array is 1238 it sould return me 368->396->397->1238Kamran Kamilli