Reputation: 33618
I have these following values from a db using mysql_fetch_assoc()
Id - Val
0 - TextA
0 - TextB
1 - TextC
2 - TextD
2 - TextE
3 - TextF
I need to add these values into an array in php which can club values like this
0 - TextA,TextB
1 - TextC
2 - TextD,TextE
3 - TextF
Upvotes: 0
Views: 55
Reputation: 9030
$organized = array();
foreach($rows as $r)
{
if (!isset($organized[$r['Id']]))
{
$organized[$r['Id']] = array();
}
$organized[$r['Id']][] = $r['Val'];
}
Upvotes: 2
Reputation: 58444
Keep it in something like this.
array(
0 => array( 'TextA', 'TextB' ),
1 => array( 'TextC' ),
2 => array( 'TextD', 'TextE'),
3 => array( 'TextF')
);
You can fill it with:
$array = array();
foreach ( $data as $item )
{
$id = $item['id'];
if ( !array_key_exists( $id , $array))
{
$array[$id] = array();
}
$array[ $id ][] = $item['value'];
}
Upvotes: 2