/    Sign up×
Community /Pin to ProfileBookmark

sort 2-d array

Learning PHP. Have a quick question that I hope someone can help me with. simple problem: I have a 2-d 5 column array. First 3 columns are char, and the other 2 are numeric. I would like to sort the array in (1) ascending order of col3, within which (2) ascending order of col4 (when 2 or more rows have same col3).

Whoever can provide me the code, please no user-defined function! I just need basic PHP code; still learning the syntax….. Thanks in advance!

to post a comment
PHP

3 Comments(s)

Copy linkTweet thisAlerts:
@NogDogFeb 19.2006 — [code=php]
<pre>
<?php
$data = array(array("a","b","c",2,2),
array("a","b","c",1,1),
array("c","b","a",1,1),
array("c","b","a",2,2));
echo "unsorted:n";
print_r($data);
foreach($data as $key => $val)
{
$i2[$key] = $val[2];
$i4[$key] = $val[4];
}
array_multisort($i2, SORT_ASC, SORT_STRING, $i4, SORT_ASC, SORT_NUMERIC, $data);
echo "sorted:n";
print_r($data);
?>
</pre>
[/code]

For more info, see http://www.php.net/array_multi_sort (particularly Example 3).
Copy linkTweet thisAlerts:
@datalineauthorFeb 19.2006 — Hey Nog!

What the heck was that????? Just kidding! I have been away from programming for some time PLUS I'm learning PHP. That code snipet just kind of blew me away. Anyway, I incorporated it in what I'm doing, and it works like a charm (I think the 4 in the sample should be a 3 - col 4). Thanks a bunch! Thanks also for the PHP.NET link. That is going to be another source of info for me beside Webdeveloper.

DL
Copy linkTweet thisAlerts:
@NogDogFeb 19.2006 — I had to do something along that line a while back, found the function and example I cited on php.net, used it, and then figured out how it worked after the fact. ?
×

Success!

Help @dataline spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...