Solved

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

Posted on 2012-03-13
2
171 Views
Last Modified: 2012-04-02
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

0
Comment
Question by:glynco
2 Comments
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 37715480
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.
0
 
LVL 31

Accepted Solution

by:
Marco Gasi earned 500 total points
ID: 37715497
You could try this:

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

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

$articles[get_class($tempObject)][$tempObject -> title] = $tempObject;

}
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Wordpress French and English Site 6 74
Is there a simpler dropbox system? 10 34
Change background color in td if any value is 1 9 23
Inserting data into database 10 34
Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
The viewer will learn how to count occurrences of each item in an array.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

789 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question