0

I'd like to fill an array with data from my database. I created a for loop for that but I think I'm doing something wrong (I'm still very new to programming so sorry for that!)

 for($i=0; $i<count($uploadprofile->getAgencies()); $i++){
  foreach($uploadprofile->getAgencies() as $agency) {
    $users[$i] = $agency->getAgencyUser();
    }
  }
  dump(count($users));

The dump statement only counts 1 user even though there are supposed to be 3 users in there.

I need this array for then using the data in an other for loop afterwards:

   for($i=0; $i<count($users); $i++){
    foreach($users as $user){
      $manager->addNotification($user->toArray()[$i], $notif);
    }
  }

I am sure this is really bad coding. It looks like way too many lines for something that simple. So I would be really glad about any advice rather than just a "downvoting"!

If more information about the entities are needed, I'd be happy to provide them!

1 Answer 1

2

Unless I'm missing something, you have too many loops, and I would stick with foreach. To build the $users array:

foreach($uploadprofile->getAgencies() as $agency){
    $users[] = $agency->getAgencyUser();
}

To use it:

foreach($users as $user){
    $manager->addNotification($user->toArray(), $notif);
}

But, if you won't actually need the $users array after this then just combine:

foreach($uploadprofile->getAgencies() as $agency){
    $user = $agency->getAgencyUser();
    $manager->addNotification($user->toArray(), $notif);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much for your quick answer! I just tried it your way but when doing dump(count($users)) the number is still 1 but not 3. any ideas why this could be? :)
Oh and I tried your cut-down-solution as well, the only problem with that is, that the first argument given to the addNotification method can't be an array. That's why I added the exact location ([$i]). But I bet there is a smoother way to solve this, too! Would love to hear it! :D

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.