Sudoscience
Sudoscience

Reputation: 301

Storing information in an array from foreach loop php

If I have a loop like this, and an array which stores information:

$itemArray = array();
foreach ($a->getDetails() as $b) 
{
    if ($b->getValue1() !== $b->getValue2()) 
    {
        if (!array_key_exists($b->getId(), $itemArray))
        {
            $itemArray[$b->getId()] = array('name' => $b->getName(), 'age' => $b->getAge());
        }

    $personName = $itemArray[$b->getId()]['name'];
    $personAge  = $itemArray[$b->getId()]['age'];

    $content    = ('Name is: ' . $personName . ', age is: ' . $personAge);
    }
}

Right now this only outputs a single 'person' for a single value of $b which is mismatched, how would I go about storing multiple values of $b being mismatched?

I basically want the output to be something along the lines of:

Name is: Dave, age is 30.

Name is: John, age is 40.

But right now only one 'person' would get output even if there were two instances where

$b->getValue1() !== $b->getValue2()

A sample output of $a->getDetails():

array(1) {
[0]=>
  object(PersonDetail)#322 (41) {
["collItemTemplateFieldPersonValues":protected]=>
NULL
["id":protected]=>
int(2375434)
["person_id":protected]=>
int(2184229)
["person_details_id":protected]=>
int(4563874)
["person_details_type_id":protected]=>
NULL
["name":protected]=>
string(4) "Test"
["person_namecode":protected]=>
string(9) "PERSON_ID"
["person_age":protected]=>
int(30)

Upvotes: 3

Views: 313

Answers (1)

Halayem Anis
Halayem Anis

Reputation: 7785

You've already stored all you need in array, you've just to loop through :)

$itemArray = array();
foreach ($a->getDetails() as $b) {
    if ($b->getValue1() !== $b->getValue2()) {
        if (!array_key_exists($b->getId(), $itemArray)) {
            $itemArray[$b->getId()] = array('name' => $b->getName(), 'age' => $b->getAge());
        }
    }
}
if (count($itemArray) > 0) {
    foreach($itemArray as $item) {
        $personName = $item['name'];
        $personAge  = $item['age'] ;
        $content    = ('Name is: ' . $personName . ', age is: ' . $personAge);
    }
}

Upvotes: 1

Related Questions