▼  Site Navigation Main Articles News Search  ▼  Anime + Manga Anime Reviews Anime Characters Gallery Screenshots Manga Reviews  ▼  Misc Links to Webcomics Bible Quotes About Older Musings
site version 7.3
PHP –– Sorting Arrays
written by: admin


Date Written: 8/28/07 Last Updated: 9/28/17

Applications include:

sort into groups,
sort based on specialized data
break a text document into relevant data to be reorganized.


Sort by letters and numbers –– case insensitive
<?php
$text="A
b
C
d";
$text=explode("\r\n",$text);
natcasesort($text);
$text=implode("<br>",$text);
echo $text;
?>

produces:
A
b
C
d


usort()

Functions are very confusing for me.  Here is an example of one I created a while back.  It will sort 4 words examining the third letter to the end of the word.

<?php
function tag($a, $b) {return (substr($a,2) > substr($b,2));}
$a=array('that','next','big','this');
usort($a,'tag');
print_r($a);
?>

produces:
Array ( [0] => that [1] => big [2] => this [3] => next )
tag is the name of the function.  return used in a function like this will calculate the answer.  usort is a user defined sort using the tag function.  $a and $b in line 2 are only examples.  $apple and $elephant would work just fine and are not related to the array $a.

usort()


Reverse natcasesort()

This is pretty simple, but it may not occur to you right away as a way to do a reverse sort of an array in natural order that is case insensitive.
<?php
$text="egg is the great breakfast food
What time is it?
the bigger they are...";
$text=explode("\r\n",$text);
natcasesort($text);
$text=array_reverse($text);
$text=implode("<br>",$text);
echo"$text";
?>

produces:
What time is it?
the bigger they are...
egg is the great breakfast food
natcasesort()


Sort Using Two Parameters

<?php
function tag($a, $b) {return (substr($a,-9) > substr($b,-9));}
$a=array('that--DIRECTORY','next--DIRECTORY','big','this','dad--DIRECTORY','fruit','apple--DIRECTORY','aaaaaaaaaaaa');
usort($a,'tag');
foreach ($a as $k => $v)
{
$pos = strpos($v, '--DIRECTORY');
if ($pos !== false)
{
$pos=$k;
break;
}
}

foreach ($a as $k => $v)
{
$pos1 = strpos($v, '--DIRECTORY');
if ($pos1 !== false)
{
$pos2++;
}
}

$begin=array_splice($a,$pos,$pos2);
natcasesort($begin);
$end=$a;
natcasesort($end);
$a=array_merge($begin,$end);
if ($pos===false) natcasesort($a);
print_r($a);
?>

The following example from http://www.dynamicdrive.com/forums/showthread.php?t=50204 does the same thing using a function:

<?php

// define your list
$a = array(
    'that--DIRECTORY',
    'next--DIRECTORY',
    'big',
    'this',
    'dad--DIRECTORY',
    'fruit',
    'apple--DIRECTORY',
    'aaaaaaaaaaaa'
    );
// call the function and pass your list to it
$sortedList = DIRsort($a);

function DIRsort($list){

    // temp array to hold values with "--DIRECTORY"
    $dirSubList = array();
    // temp array to hold non-"--DIRECTORY" values
    $subList = array();

    // loop through each item in array
    foreach($list as $li){
        // if "--DIRECTORY" is found, place value in $dirSubList array
        if(strstr($li, '--DIRECTORY')){ $dirSubList[] = $li; }
        // if not, place in $subList array
        else{ $subList[] = $li; }
    }
    
    // sort each array alphabetically
    sort($dirSubList);
    sort($subList);
    // recombine the two arrays
    $List = array_merge($dirSubList, $subList);
    
    // send the properly sorted list back to the script
    return $List;
}
?>


both will produce:
Array ( [0] => apple––DIRECTORY [1] => dad––DIRECTORY [2] => next––DIRECTORY [3] => that––DIRECTORY [4] => aaaaaaaaaaaa [5] => big [6] => fruit [7] => this )


Sort by newlines

<STYLE TYPE="TEXT/CSS">
textarea{background-color:#a9a9a9;color:black;}
body{
background-color:tan;
}
</style>
<?php $data=$_POST['data'];
$data=explode("\r\n",$data);
natcasesort($data);
$data=implode("\r\n",$data);
?>
<form action=<?php echo $_SERVER['PHP_SELF']; ?> method="POST">
contents of the web file:<br><textarea name="data" cols=115 rows=32><?php print htmlentities($data);?>
</textarea><br><br>
<input type='submit' name="queryButton" value="Submit">
</form>

Load the above as a file and you will have a search program that sorts each "line" alphanumerically.  A line is every segment of the data that is separated by a newline \r\n.  I use this program when I want to sort the typed in addresses file that opera has.

You can try it out here.


Analyze a text document and turn it into a multidimensional array and make calculations based on the data

The following is a script that can take text, analyze it and turn it into a multidimensional array.  The text will be divided and sorted by newlines on and whitespace.

The identifier mentioned is the first three terms on a line to help identify what line is to be looked at.  When the script finds the line it will take the fourth term, whether letter or number, and put it into a string for storage.  The script will repeat this process until all the identifiers have been searched for and the key values (the fourth term on the line where the identifier is located) are entered into a string.  

The output will state where each value was found as well as add all of the values in the storage string stating what the sum is.

For example if the data is
sdf sdf sdf 4
sdf
sdf sdf sdf 7
and the identifyer is
sdf sdf sdf
Then the output will be:
Result 1 is located at array[0][1].4
Result 2 is located at array[2][1].7
.

If you add the values of these identifiers together you will get 11
Kind of a limited program really, but it has potential.
<STYLE TYPE="TEXT/CSS">
textarea{background-color:#a9a9a9;color:black;}
body{
background-color:tan;
}
</style>
<?php
$data=@$_POST['data'];
$one=@$_POST['one'];
$one=str_replace(" ","",$one);
$onearr=explode(",",$one);
$url=@$_POST['url'];

if ($url != "")  
{
$handle = file_get_contents("$url",NULL);
$data=htmlentities($handle);
}

$string="";
$arr=array_map(create_function('$a', 'return preg_split(\'[\s+]\', $a);'), preg_split('/\n/', $data));

$oops2=count($onearr);
$oops=count($arr);
$a=0;
while ($a<$oops)
{
$arr2  =$arr[$a][0];
$arr2 .=$arr[$a][1];
$arr2 .=$arr[$a][2];
array_unshift($arr[$a],$arr2);
array_unshift($arr[$a],"nerfed");
$a++;
}
?>

<form action=<?php echo $_SERVER['PHP_SELF']; ?> method="POST">
copy and place your data in here or enter the url where the data is stored<br>in the space provided at the end:<br>
             <textarea name="data" cols=55 rows=25><?php echo "$data"; ?></textarea><br>
identifiers (remember to separate identifiers with commas): <br><textarea name= "one" cols=45 rows=3><?php echo "$one"; ?></textarea><br>

url of .txt document to scan (optional): <br><input type="text" name="url" size=75 value=<?php echo @$_POST['url']; ?> >
<br><br>
<input type='submit' name="queryButton" value="Submit and Add">
</form>

<?php
$a=0;$b=0;$c=0;$d=array(0);
while ($b<$oops2) {
while ($a<$oops) {  
$ans=array_search($onearr[$b],$arr[$a]);
if ($ans==1) {$c++;echo "Result $c is located at array[$a][$ans].";
array_push($d,$arr[$a][5]);
echo $arr[$a][5];
echo "<br>";}
$a++;
}$b++;$a=0;
}

$ans1=array_sum($d);
echo ".<br><br>If you add the values of these identifiers together you will get $ans1";
?>

The following line is what creates the multidimensional array that is divided by newlines and spaces:

$arr=array_map(create_function('$a', 'return preg_split(\'[\s+]\', $a);'), preg_split('/\n/', $data));



Turn an array into a multidimensional array
<?php
$ar=array('me ss','w e','as df','e d');
$ar[0]=explode(' ',$ar[0]);
print_r($ar);
?>



chop a file up into a multidimensional array by comma and newlines
<STYLE TYPE="TEXT/CSS">  
textarea{background-color:#a9a9a9;color:black;}  
body{  
background-color:tan;  
}  
</style>  
<?php
$data=@$_POST['data'];
$url=@$_POST['url'];

if ($url != "")  
{  
$handle = file_get_contents("$url",NULL);  
$data=htmlentities($handle);  
}
$arr=array_map(create_function('$a', 'return preg_split(\'[,]\', $a);'), preg_split('/\n/', $data));
?>  

<form action=<?php echo $_SERVER['PHP_SELF']; ?> method="POST">  
copy and place your data in here or enter the url where the data is stored<br>in the space provided at the end:<br>
the data will be sorted based on commas and newlines.<br>
<textarea name="data" cols=55 rows=25><?php echo "$data"; ?></textarea><br>  
url of .txt document to scan (optional): <br><input type="text" name="url" size=75 value=<?php echo @$_POST['url']; ?> >  
<br><br>  
<input type='submit' name="queryButton" value="Submit and Add">  
</form>  

row 1 col 1 has a value of <?php print $arr[0][0]; echo "<br><br>  

<pre>";
print_r($arr);  
echo"</pre>";
?>



40 most common words in a text file

<?php
$text = file_get_contents("http://www.mysite.com/test.txt",NULL);
$text=str_replace("\r\n"," ",$text);
$text=preg_replace('/[^a-zA-Z\s]/','',$text);
$text=preg_replace('/(\s){2,}/',' ',$text);
$text=strtolower($text);
$text=explode(" ",$text);
$out=array_count_values($text);
arsort($out);
$out=array_slice($out,0,40);
echo"<pre>";
print_r($out);
echo "</pre>";
?>



related

misc –– count marvel digital comics This shows an example where a multidimensional array is created from a text document and then sorted via array_sum.
PHP –– array manipulation

TAGS: php
copyright 2005–2024