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.
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);
}
}
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);}
}