Question:
how to use PHP to sort this?
2007-07-12 16:40:35 UTC
i have a file with this:

|jack|16|
|bob|19|
|nikki|17|

how would I sort it so it would become sorted in alpehbetical order:

|bob|19|
|jack|16|
|nikki|17|
Six answers:
diagnostix
2007-07-13 00:03:24 UTC
1. read the file content line by line and explode() the items into an array.



$handle = @fopen("/tmp/inputfile.txt", "r");

if ($handle) {

while (!feof($handle)) {



//read in the line

$line = fgets($handle, 4096);



//explode it into array elements

$linedata = explode('|',$line);



//remove the 1st element cos it's empty

array_shift($linedata);



//remove the last element cos it's empty too

array_pop($linedata);



//store each line into mydataarray

$mydataarray[] = $linedata;



}

fclose($handle);

}



2. Now you have $mydataarray which is an array of arrays, which looks like this.



Array (

'0' => Array ( '0' => 'jack', '1' => '16'),

'1' => Array ( '0' => 'bob', '1' => '19' ) ,

'2' => Array ( '0' => 'nikki', '1' => '17' )

);



3. just use the array_multisort() function, and you should get what you need.

array_multisort($mydataarray, SORT_ASC);



hope that helps
madludwigv
2007-07-13 00:50:03 UTC
Im not entirely sure how how you're reading in the information. How the file is read in is important to know as well. Odds are if you use the fopen of php you'll get that string and then parse it which will return an array, you could have it reutrn an array of arrays which is pretty standard for php.



So you'll have $a = [ ["jack", 16], ["bob", 19], ["nikki", 17]]



To sort it the way you want you'll have to use a custom function.



uksort($a, "cmp");



function cmp($a, $b)

{

/**Then compare the $a[0] to the $b[0]

if the values are the same return 0

if $a[0] > $b[0] return 1

else return -1



These are the sort values it will know how to use the info returned from them.

**/

}
Pekoe200
2007-07-13 01:00:32 UTC
If the file is small, I'd do it as follows, since this method loads the entire file into memory. If its a 100 meg file, I wouldn't recommend this method.





$file = '/path/to/file';



//load the entire contents of the file into an array

$input = file($file);



//sort the array alphabetically

sort($input);



//write the changes back to the orignal file

file_put_contents($file,$input);
Ludoooooo
2007-07-13 00:35:19 UTC
put the names in array like that




//assigning the names to array

$xarray['0']= "jack";

$xarray['1']= "bob";

$xarray['2']= "nikki";

//sorting

sort($xarray);



for($i=0; $i<2; $i++)

{

echo $xarray[$i] . "
";

}

?>
tutorials
2014-04-15 14:01:27 UTC
Php Array sort function very useful for your question...

Demo:
2014-11-07 05:13:33 UTC
confusing matter. lookup on to a search engine. that will might help!


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...