Avatar of glynco
glynco
 asked on

Assigning associative array key in an array in just one loop.

How can I combine these two loops in to one loop?

for ($i = count($objs)-1; $i >= 0; $i--) { 

$tempObject = new Article();
$tempObject -> title=$objs[$i];
$tempObject -> author="My Author: " . $i;

array_push($articles[get_class($tempObject)], $tempObject);

}

foreach ($articles['Article'] as $my_object)
{
    $title = (string)$my_object->title;
    $my_associative_array[$title] = $my_object;
}

Open in new window

PHP

Avatar of undefined
Last Comment
Marco Gasi

8/22/2022 - Mon
Ray Paseur

What are you trying to accomplish here?  It looks like you have two different arrays in play.  Unless these arrays are hundreds of thousands of elements long, there is no economy in combining these loops and plenty of potential for making a programming error.

If you have some test data, please post it, thanks.
ASKER CERTIFIED SOLUTION
Marco Gasi

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck