Sorting array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
martelo59
Forum Newbie
Posts: 6
Joined: Sat Oct 22, 2011 3:55 am

Sorting array

Post by martelo59 »

Hello, I need little help. I have textual database example sctipt in form
[$id]|$id|$data1|$data2|[$id]
and I need sorting array by minimum, maximum and alphabet. You can see at my example how i showing data without sorting.
Country.txt

[1][]|1|USA|15|[1][2][]|2|Mexico|12|[2][3][]|3|Austria|11|[3][4][]|4|France|8|[4][5][]|5|Singapore|4|[5]

Code: Select all

<?php

$dat = substr(file_get_contents("country.php"),0,100000000000);
$datsum = substr_count($dat, '[]');

for ($i=$datsum;$i>=1;$i--)
{
$stra = explode("[]", $dat);
$a = explode('|', $stra[$i]);

echo "$a[2] $a[3]<br>";

}

?>
The above example will output:

Singapore 4
France 8
Austria 11
Mexico 12
USA 15
I need sorting by alphabet. The above example that i need output:
Austria 11
France 8
Mexico 12
Singapore 4
USA 15
I need sorting by max, min. The above example that i need output:
Singapore 4
France 8
Austria 11
Mexico 12
USA 15
Thanks for answers. ;)
genix2011
Forum Commoner
Posts: 74
Joined: Tue Aug 02, 2011 4:00 pm

Re: Sorting array

Post by genix2011 »

Hi,

simple asort and ksort should be sufficient.

Code: Select all

<?php

$dat = substr(file_get_contents("country.php"),0,100000000000);
$datsum = substr_count($dat, '[]');

$sort = array();
for($i=$datsum;$i>=1;$i--){
	$stra = explode("[]", $dat);
	$a = explode('|', $stra[$i]);
	$sort[$a[2]] = $a[3];
}


$sort_key = $sort;
ksort($sort_key);

$sort_val = $sort;
asort($sort_val);
?>
In $sort_key you'll find the array sorted by the country name and in $sort_val you'll find the countries sorted by the value.

Greets.
martelo59
Forum Newbie
Posts: 6
Joined: Sat Oct 22, 2011 3:55 am

Re: Sorting array

Post by martelo59 »

Hello,

thank you very much for your answer. I have a little problem, how i can print this in form, for example:
Austria 5
USA 14
Singapore 3
and one more question, if i have more variable, for example, what is syntax for splitting in array?

Thank you
[$id]|$id|$data1|$data2|$data3|$datax|[$id]
martelo59
Forum Newbie
Posts: 6
Joined: Sat Oct 22, 2011 3:55 am

Re: Sorting array

Post by martelo59 »

Hello,

i was resolved my problem. Here is code if any other need. Thank you for your help. ;)

Code: Select all

<?php

$dat = substr(file_get_contents("country.txt"),0,100000000000);
$datsum = substr_count($dat, '[]');

$sort = array();
for($i=$datsum;$i>=1;$i--){
        $stra = explode("[]", $dat);
        $a = explode('|', $stra[$i]);
        $sort["$a[2]"] = "[$a[1]]|$a[1]|$a[2]|[$a[1]]";
}


$sort_key = $sort;
ksort($sort_key);

$sort_val = $sort;
asort($sort_val);

foreach ($sort_key as $key => $val) {
    echo "$val";
}

?>
Post Reply