1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

grouping using php script

Discussion in 'PHP' started by hanliong, Feb 28, 2008.

  1. hanliong

    hanliong New Member

    Joined:
    Dec 21, 2007
    Messages:
    7
    Likes Received:
    0
    Trophy Points:
    0
    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.
     
  2. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    Say the data you have is in a file, you'll need to use associative arrays to get the job done!

    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.
     
  3. hanliong

    hanliong New Member

    Joined:
    Dec 21, 2007
    Messages:
    7
    Likes Received:
    0
    Trophy Points:
    0
    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:

    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
     

Share This Page