0

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
6
  • 2
    Can't you do this at the db query? I had a similar requirement when using MySQL so I used group_concat - very handy. Commented May 10, 2011 at 19:03
  • I assume you are getting the data as an array? Commented May 10, 2011 at 19:04
  • @user519575: that's a good suggestion. I'd recommend posting it as an answer :) Commented May 10, 2011 at 19:05
  • @MeLight: the input format is unclear :/ I'm guessing he isn't getting the data as anything right now, and is just deciding what to put inside the loop where he's running mysql_fetch_array. Commented May 10, 2011 at 19:05
  • 1
    I read this incorrectly as wanting string array values (TextA,TextB). Commented May 10, 2011 at 19:10

2 Answers 2

2

$organized = array();

foreach($rows as $r)
{
  if (!isset($organized[$r['Id']]))
  {
    $organized[$r['Id']] = array();
  }
  $organized[$r['Id']][] = $r['Val'];
}

Sign up to request clarification or add additional context in comments.

Comments

2

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'];
}

Comments

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.