Solved

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

Posted on 2012-03-13
2
155 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 108

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 30

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

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
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 create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

760 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now