0

Within a foreach loop, I get the following values:

$name = 'foo';
$id = '1';

Now, the same name may appear multiple times with different ID's and I would like to form as array like this:

$data = array('foo' => array('1','2','3'), 
              'bar' => array('4','7','98'),
              'nee' => array('12','45','45'));

I have tried:

$data = array();

foreach ($rows as $row)
{
   $name = $row->name;
   $id = $row->id;

   $data[$name] = $id;
}

However, All this returns is:

The last value:

$data = array(   'foo' => '3', 
                  'bar' => '98',
                  'nee' => '45');

So not too sure how to do this.

2 Answers 2

1

You need to append to the sub-array, not assign it directly. And if $name doesn't yet exist, you need to add it.

$data = array();
foreach ($rows as $row)
{
  $name = $row->name;
  $id = $row->id;
  if (isset($data[$name])) {
    $data[$name][] = $id;
  } else {
    $data[$name] = array($id);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

If there is no value for your name , you need just to add it , else you append value to existing ones :

$data = array();

foreach ($rows as $row)
{
   $name = $row->name;
   $id = $row->id;

    if (isset( $data[$name]) && is_array( $data[$name]) ) {
       $data[$name][] = $id; 
    }
    else {$data[$name] = array($id);}


}

2 Comments

What if $name not exists in $data for first time ?
Okey i add else statement :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.