asort/arsort issues with my array, arises on table creation

68 Views Asked by At

I can't seem to get asort/arsort working right with my code. I originally was using sort/asort. When I print_r the array appears sorted by then I move on to my "createtable" function and it just prints the values in indexed order. Any ideas whats going on?

Segment of code in my main file

//Sorts Array by value [Ascending] 
asort($songArray);
print_r($songArray);

//Creates table [See inc_func.php]
CreateTable ($songArray); 

Referenced Function

function CreateTable ($array)
{
/* Create Table:
 *  count given $array as $arrayCount
 *  table_start
 *  for arrayCount > 0, add table elements
 *  table_end
 */   

$arrayCount = count($array);
echo '<table>';
echo '<th colspan="2"> "Andrews Favorite Songs"';

// as long as arraycount > 0, add table elements
for ($i = 0; $i < $arrayCount; $i++)
{ 
    $value = $array[$i];
    echo '<tr>';
    echo '<td>'.($i+1).'</td>';
    echo '<td>'.$value.'</td>';
    echo '</tr>';
}

echo '</table>'.'<br>'; 
}  

Thank You.

1

There are 1 best solutions below

0
Steve On

Sorting an array does not alter the keys, just reorders them

Your display code then iterates the array in numerical order, so the order is ignored.

Instead use a foreach loop:

function CreateTable ($array)
{
    echo '<table>';
    echo '<th colspan="2"> "Andrews Favorite Songs"';
    $count = 1;
    foreach ($array as $value)
    {
        echo '<tr>';
        echo '<td>'.$count++'</td>';
        echo '<td>'.$value.'</td>';
        echo '</tr>';
    }

    echo '</table>'.'<br>';
}