• There is NO official Otland's Discord server and NO official Otland's server list. The Otland's Staff does not manage any Discord server or server list. Moderators or administrator of any Discord server or server lists have NO connection to the Otland's Staff. Do not get scammed!

Sort function in php??

tosse12

Panchira Project Member
Joined
Jun 10, 2007
Messages
864
Reaction score
9
Location
Sweden
Hi members of OtLand!

I am having some problems to create a sort fuction in my code (For spells)

PHP:
<style type="text/css">
td {
    color: white;
    height: 20px;
    color: #666;
}

</style>
<?php 

if(!defined('BASEPATH')) exit('No direct script access allowed'); 

$DIR = '*:/*/*/data/spells/'; 
     
if(is_dir($DIR)) { 
    $spells = simplexml_load_file($DIR.'spells.xml'); 
	$table_color_1 = 'black';
	$table_color_2 = '#080808';
?> 
<h2>Spells</h2>
<table style= border="0px" cellspacing="0px" cellpadding="4px" width="100%">
<tr  bgcolor="#101010 ">
<th style="color: #FF4500">Spell Name</th>
<th style="color: #FF4500">Words</th>
<th style="color: #FF4500">Mana Cost</th>
<th style="color: #FF4500">Level Required</th>
</tr>

<?php

$i = 1;
foreach($spells as $spell) {
$color = ($i % 2 ? $table_color_1 : $table_color_2);
$i++;

    echo '
	<tr bgcolor="'.$color.'" id="spell_list">
		<td style="font-size: 10pt;">'.$spell['name'].'</td>
		<td style="font-size: 10pt;">'.$spell['words'].'</td>
		<td style="font-size: 10pt;">'.$spell['mana'].'</td>
		<td style="font-size: 10pt;">'.$spell['lvl'].'</td>
	</tr>';
}

}
else{alert('Error while loading spells. Directory address must be correct.');}
?>
</table>
I am not sure where and how I shall add the sort function.

I would like that Spell Name to be sorted.

If I am unclear, Could you please tell me which part that's unclear!

Thanks in advance!
 
Last edited:
sort() won't work you should write your own sorter looking at attribute you want to sort by. Look also at function multisort() but better is usort() and remmeber that you are sorting array of objects.

I found solution in net but not for simplexml

PHP:
?php
//  DOM creation (working)
$doc = new DOMDocument();
$doc->preserveWhiteSpace = false;


//  XML loading (working)
$doc->load("news2.rss");
$root = $doc->documentElement;


// get array $news from myItem nodes (Working)
$news= $root->getElementsByTagName('myItem');




//function to reorder the $news array (Not working)

function my_sort($a, $b) 
{ 
    $compare1 = strcmp($news->item($a)->getAttributeNode('id')->value, $news->item($b)->getAttributeNode('id')->value); 
    if ( $compare1 > 0 ) 
    { 
        return $compare1; 
    } 
} 
usort($news, "my_sort");



// Save the update xml file

print $doc->save("news2.rss");

with example of sorting objects using usort()
 
Back
Top