简体   繁体   中英

Php fill array with for loop

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!

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM