Solved

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

Posted on 2012-03-13
2
186 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 110

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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

This article discusses four methods for overlaying images in a container on a web page
Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to count occurrences of each item in an array.

623 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