471,109 Members | 1,352 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,109 software developers and data experts.

How to sort the sum of columns in a delimited txt flat file?

Hello!

I am stuck with this. Can anyone help me?

I have some rows in a text file. That I need: sum from selected columns and then sort the rows depending on the sum result and print the 10 larger sum results.

I have a part in this incomplete script that works but I cant put the array in this calculation. After this I try something else but there I need to sort the rows of it (depending on the sum of some columns that is being echoed.

Thanks in advance!!

data.txt is the txt that contains the records and here is the code of php:

Expand|Select|Wrap|Line Numbers
  1.  
  2. <?php
  3.  
  4. function topTenDistricts($arr, $len) {
  5.  
  6. for ($i=0; $i < $len; $i++) {
  7.     for ($j=0; $j < $len-1; $j++) {
  8.         if ($arr[$j+1] > $arr[$j]) {
  9.             $temp = $arr[$j];
  10.             $arr[$j] = $arr[$j+1];
  11.             $arr[$j+1] = $temp;
  12.         }
  13.     }
  14. }
  15. for ($k=0 ; $k < $len; $k++)
  16. print($arr[$k] . "\n");
  17.  
  18. }
  19.  
  20. //// example of previous array sorting ->> topTenDistricts($mydata, 10);
  21. //$mydata = array();
  22. //$mydata[0] = 12;
  23. //$mydata[1] = 4;
  24. //$mydata[2] = 44;
  25. //$mydata[3] = 3;
  26. //$mydata[4] = 6;
  27. //$mydata[5] = 32;
  28.  
  29. $max = 0;
  30. $file = file("data.txt");
  31. $r=0;
  32. $sum=array();
  33. foreach ($file as $line){
  34.     list($row[$r]['partno'], $row[$r]['title'], $row[$r]['color'], $row[$r]['width'], $row[$r]['length'], $row[$r]['height'], $row[$r]['time'], $row[$r]['price'], $row[$r]['place']) = split(";", $line);
  35.     $sum[r]=$row[$r]['color'] + $row[$r]['width'] + $row[$r]['length'] + $row[$r]['height'] + $row[$r]['time'] + $row[$r]['price'] + $row[$r]['place'];
  36.     //echo 'Name DD. : '.$row[$r]['title'].' | Sum : '.$sum.'<br>';
  37.     echo 'Name DD. :'.$row[$r]['title'].'with :'.$sum[r].' records<br>';
  38.     $r++;
  39.     if ($sum >= $max) {
  40.                 $max = $sum;
  41.                 $title = $row[$r]['title'];        
  42.                 }
  43.     }
  44.  
  45.  
  46.  
Attached Files
File Type: txt data.txt (2.0 KB, 292 views)
Jan 26 '11 #1
0 989

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

2 posts views Thread by BT3 | last post: by
2 posts views Thread by platinumbay | last post: by
2 posts views Thread by Neural | last post: by
3 posts views Thread by PaulH13 | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.