PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, January 30, 2022

[FIXED] how to add array or row to array while foreach looping laravel 5.8

 January 30, 2022     laravel-5, php, recursion     No comments   

Issue

I need to get all products for category and sub categories when click on parent category

so i make loop or recursive loop to get all id for category and subcategory to search for its products

public function tree($category, $cats = array())
{
    $items = category_model::select('id')->where('parent_id', $category)->get();
    foreach ($items as $key=>$value)
    {
        //$cats = $value;
        $cats = Arr::add($cats, 'id', $value);
        self::tree($value, $cats);
    }
    return $cats;
}

public function allproduct(Request $request)
{
    return self::tree($request->id);
}

I have tried this code but looping with our result

I need to add this all id to make search for products through this array


Solution

You can improve your own code and make it work by taking all the category ids at once, instead of making a for each loop there.

Also, you are missing a terminating condition which is a must when using recursive functions.

Also, you don't need to process the same ids again and again if they have already been processed.

Taking all those points in mind, do something like this:

public function tree($cats, $alreadyProcessedCats = [])
{
    if (empty($cats)) {
        return [];
    }
    $newCatIds = [];
    foreach ($cats as $catId) {
        //do not process it if it was alreadt processed
        if (in_array($catId, $alreadyProcessedCats)) {
            continue;
        }
        //fetch all the categories id where parent id is one of the id which is present in the $cats
        $items = category_model::where('parent_id', $category)->pluck('id');
        if (empty($items)) {
            continue;
        }
        $items = $items->toArray();
        $newCatIds = array_merge($newCatIds, $items);
    }
    //terminal condition
    if (empty($newCatIds)) {
        return $cats;
    }
    $newCats = array_merge($cats, $newCatIds);
    return self::tree($newCats, $cats);
}

public function allproduct(Request $request)
{
    $allCategoriesIds = [$request->id];
    $allCategoriesIds = self::tree($allCategoriesIds);
}


Answered By - Abhay Maurya
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing