grouping using php script

Light Poster
28Feb2008,12:26   #1
hanliong's Avatar
Hi all,
i have a data like this:
1#test
2#test
3#test2
4#test
5#test2
6#test2
7#test3

i would like to group these with PHP, not mysql, since it just PHP file, not mysql.
I want the output is:
- test: 1|2|4|
- test2: 3|5|6|
- test3: 7|

How can i do that with PHP?
Thanks, need for your help, since i just a newbie with PHP. Can find any help at search engine.
Team Leader
28Feb2008,13:45   #2
pradeep's Avatar
Say the data you have is in a file, you'll need to use associative arrays to get the job done!

Code: PHP
$arr = array();
// Read the data an get it into array $data
foreach($data as $v)
{
  list($val,$key) = explode('#',$v);
  if(isset($arr[$key]))
  {
    $arr[$key] .= "$val|";
  }
  else
  {
    $arr[$key] = $val;
  }
}

So you just print out the array $arr to get the desired output.
Light Poster
29Feb2008,08:03   #3
hanliong's Avatar
Hi Pradeep,
Thanks for your help. At the beginning, i just feel that i have to use foreach. but i have no idea how to do that.

You help me out of this case.
But i still get the problem.
i make the script like this:

Quote:

$data=array('1#test','2#test','3#test2','4#test',' 5#test2','6#test2','7#test3');
$arr = array();
// Read the data an get it into array $data
foreach($data as $v)
{
list($val,$key) = explode('#',$v);
if(isset($arr[$key]))
{
$arr[$key] .= "$val|";
}
else
{
$arr[$key] = $val;
}
print $arr[$key];
}
and the result is: 112|312|4|35|35|6|7
i just want, the result is: test:1|2|4|;test2:3|5|6|;test3:7|
So, i can explode the result to get the value of test, test2 and test3.
Can you help me?
And Pradeep, can you help me to teach about class and function? Where the article i can read and learn. I mean the simple one, that i can learn better.

Thanks