SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Hybrid View

  1. #1
    SitePoint Addict
    Join Date
    Feb 2004
    Location
    Rome
    Posts
    296
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    working with a file

    Hello

    I have a file data.txt containing some data in this format

    house=10
    car=12
    pen=1
    house=10
    red table=2
    tables=7
    house=7
    car=7
    red table=3
    house=3
    pen=2
    ...

    and so on. I need to sum the numeric values of each string to have this result

    house=30 car=19 red table=5 tables=7 pen=3 ...

    Which is the fast way to that using php please ?

    Thank you
    Graziano
    trcris ::> http://www.trcris.com

  2. #2
    SitePoint Wizard silver trophybronze trophy Cups's Avatar
    Join Date
    Oct 2006
    Location
    France, deep rural.
    Posts
    6,869
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    Here is one way to do it.

    PHP Code:
    if(is_file("/TEMP/data.txt")){  // check file exists
    $arr file("/TEMP/data.txt"); // load it line by line into an arrat
    $new = array(); // create a blank return array
      
    foreach($arr as $row){ // loop through the lines in the file

      
    list($key,$val) = split("="$row);  // split the line into 2 variables
         
    if (key_exists($key$new) ){ // if a key already exists, 
         
    $new[$key] += (int)$val// cast the string number an integer, and add it to the existing key
         
    continue;  // drop out of this part of the loop
         
    }
      
    $new[$key] = (int)$val// other wise add a new key, and assign it the first integer, again casting it with (int)
      
    }
    }


    var_dump($new);  // look inside your array 
    Gives:
    array
    'house' => int 30
    'car' => int 19
    'pen' => int 3
    'red table' => int 5
    'tables' => int 7


    There is probably a other ways of doing this, using fgetcsv maybe, but this should teach you a few basic commands.

  3. #3
    SitePoint Addict
    Join Date
    Feb 2004
    Location
    Rome
    Posts
    296
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you very much, I will try it
    trcris ::> http://www.trcris.com


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •