0

I have this code:

foreach($categories as $category) {
  $items = getItems($category);

  foreach($items as $item) {
     // some code to manipulate $item
  }
}

As you can see, inner loop depends on outer loop. Problem is that if data is too big, this takes quite some time. Is there some way, algorithm or technique so that I can avoid inner loop that is dependent on outer loop ?

PS. I am using PHP 5.3 so yield is out of question. Also someone told me that may be recursion can be helpful here but I don't exactly know how to go about with that.

Thanks for the help

7
  • 3
    With what you've provided, I can't see any way to algorithmically avoid this. You can possibly tweak the workflow of what you're trying to do so that you don't have to manipulate the items of every category at once and instead just do a single category at a time Commented May 8, 2015 at 20:09
  • Does getItems run a database query? Commented May 8, 2015 at 20:11
  • If you can put your array code and what you expected as an output then anyone can suggest the solution Commented May 8, 2015 at 20:12
  • please add getItems's code Commented May 8, 2015 at 20:13
  • 1
    not make sense. it depends on the case. what's your desired output. Some time same output can get without inner loop and some time it's necessary. Commented May 8, 2015 at 20:19

1 Answer 1

2

One way is to avoid the nested loops is to store the data first, an then manipulate it

$items=array_map("getItems",$categories);
$items=array_reduce("array_merge",$items);
array_walk($items,"item_manipulation");

Note that this code is not more efficient than your original snippet, it's just without nested loops as you asked.

A more intelligent optimization would be (maybe) possible if we could know what getItems does, and what per-item manipulation you do

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.