473,378 Members | 1,309 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

How to sort an array, leaving one or more columns unsorted?

Greetings. I'm quite new to PHP and have very little knowledge of
programming in general, so I may be missing something obvious, but I
can't find a solution to the following difficulty in either the PHP
manual or Google.

I have a tab-delimited text file containing numerous lines of data,
which is searched for matches to a query from an HTML form. I want to
be able to sort the resulting two-dimensional array of matches by one
column only, leaving the other columns unsorted. For example, if three
lines match "bar0",

foo02 bar01 foobar foobar
foo03 bar02 foobar foobar
foo01 bar01 foobar foobar

should become

foo02 bar01 foobar foobar
foo01 bar01 foobar foobar
foo03 bar02 foobar foobar

not

foo01 bar01 foobar foobar
foo02 bar01 foobar foobar
foo03 bar02 foobar foobar

The following method works for sorting on the second column, but seems
both inelegant and inflexible (especially if I want to sort on the
third or fourth column instead:

#v+

<?php
$data = file("filename.txt");
$sortkey = 0;
foreach($data as $line) {
// if the line matches a regex, do this:
$temp = explode("\t", rtrim($line,"\n"));
$newdata[]= array($temp[1], $sortkey, $temp[0], $temp[2], $temp[3]);
$sortkey++;
}
if(sizeof($newdata) > 0) {
sort($newdata);
foreach($newdata as $line) {
echo $line[2]."\t".$line[0]."\t".$line[3]."\t".$line[4]."\n";
}
}
?>

#v-

Is there a less clumsy way of doing this kind of thing without having
to use a "real" database? I've tried all the inbuilt array-sorting
functions, without any success so far.

PJR :-)
--
Nemo hibericam exspectat inquisitionem.

alt.usenet.kooks award-winners and FAQ:
<http://www.insurgent.org/~kook-faq/>

Nov 24 '05 #1
3 1841
Peter J Ross wrote:
Is there a less clumsy way of doing this kind of thing without having
to use a "real" database? I've tried all the inbuilt array-sorting
functions, without any success so far.


Untested, but might try something like what I and subsequently rojaro
discussed at http://php.net/asort:

<?php
$data = file("filename.txt");
$sortCol = 1; // sort on second column
$aLines = []; // original data
$aSorted = []; // this will contain the resulting, sorted data
foreach($data as $line) {
// if the line matches a regex, do this:
$aLine[] = $line;
$temp = explode("\t", rtrim($line,"\n"));
$aSorted[] = $temp[$sortCol]; }
if ($aSorted) {
// sort on selected column retaining line associations
asort($aSorted);
// now replace selected column val with entire line
foreach ($aSorted as $idx => &$val) $val = $aLine[$idx];
// normalize the keys to be 0..sizeof($aSorted)-1
$aSorted = array_merge($aSorted);
// show the sorted lines
foreach ($aSorted as $line) echo "$line\n";
}
?>

Csaba Gabor from Vienna

Nov 26 '05 #2
On 25 Nov 2005 17:24:22 -0800, Csaba Gabor <Cs***@z6.com> wrote in
comp.lang.php:
Peter J Ross wrote:
Is there a less clumsy way of doing this kind of thing without having
to use a "real" database? I've tried all the inbuilt array-sorting
functions, without any success so far.


Untested, but might try something like what I and subsequently rojaro
discussed at http://php.net/asort:


It's certainly tidier than my kludge. Many thanks. If it doesn't work
after I've tested it I'll let you know.

PJR :-)
--
Nemo hibericam exspectat inquisitionem.

alt.usenet.kooks award-winners and FAQ:
<http://www.insurgent.org/~kook-faq/>

Nov 26 '05 #3
Peter J Ross wrote:
be able to sort the resulting two-dimensional array of matches by one
column only, leaving the other columns unsorted.


Does the ordering of the other columns not matter and do you just want to
avoid doing extra work, or does it specifically need to be left exactly
the way it went in?

If the former, just use usort with your own comparison function:

$col = 2; //set to right column number to sort on
function cmp($a, $b) {
global $col;
return strcmp($a[$col], $b[$col]); //or a numerical comparison perhaps
}
usort($myTwoDimensionalArray, 'cmp');

If the latter, you'll have to write your own (relatively) low-level
sorting routine because the order of identical elements is not defined for
built-in sorting routines, ie. you can't rely on them to just leave those
elements in their existing order. (unless stated thusly in the manual..).

--
E. Dronkert
Nov 26 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

19
by: David | last post by:
Hi all, A while back I asked how to sort an array of strings which would have numerals and I wanted to put them in sequential numerical order. For example: myArray = "file1"; myArray =...
21
by: yeti349 | last post by:
Hi, I'm using the following code to retrieve data from an xml file and populate a javascript array. The data is then displayed in html table form. I would like to then be able to sort by each...
4
by: christiang | last post by:
Hi guys I'd like to sort a multidimensional array that hasn't numerical index, in fact it is like: Array ( => Array ( => mobile => 1 )
1
by: veg_all | last post by:
is there an easy function/ class for sorting a 2D array multiple fields. I would like to specify a primary sort and secondary sort.
1
by: millw0rm | last post by:
i got 2 array one holds the actual data n another is user generated sort order... how to sort array #1 according to array #2???? array shld be sorted according to sortorder Array #1 ( =Array...
0
by: vinaykumar Maladkar | last post by:
Hi All, I m using Visual studio 2005 and C#. i want to show comparative data of different cars like their price , engine , capacity etc. So i am using DataGridView. but How to group one or more...
4
by: Santosh Nayak | last post by:
Hi, Is it possible to sort the array of struct based on the data members. e.g. struct { int a ; float b ; char c ; } TEMP ;
0
by: mingke | last post by:
Hi... I'm having some difficulties to sort two different array (say X and Y), these arrays state the coordinate in x and y axis..so, if X change, Y has to change. I have unsorted array and I...
0
by: George Michael | last post by:
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...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.