473,770 Members | 1,833 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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($newd ata) > 0) {
sort($newdata);
foreach($newdat a 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.kook s award-winners and FAQ:
<http://www.insurgent.o rg/~kook-faq/>

Nov 24 '05 #1
3 1864
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($aSor ted)-1
$aSorted = array_merge($aS orted);
// 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.kook s award-winners and FAQ:
<http://www.insurgent.o rg/~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($myTwoDim ensionalArray, '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
2633
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 = "file2"; myArray = "file3"; myArray = "file4"; myArray = "file5";
21
3224
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 column. Once the array elements are split, what is the best way to sort them? Thank you. //populate data object with data from xml file. //Data is a comma delimited list of values var jsData = new Array(); jsData = {lib: "#field...
4
2555
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
1726
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
2265
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 ( =1 =2
0
1315
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 columns in a single header column? i want to show like this - Maruti_800 Maruti_Zen Maruti_WagonR Price $---- $---- ...
4
5232
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
2172
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 want to eliminate array with the same value... Here's my code which doesn't work: #include <stdlib.h>
0
1061
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 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. ...
0
9617
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10257
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10037
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9904
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8931
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6710
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5354
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4007
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.