在创建表时,我的数组出现了asort/arsort问题


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

我似乎无法让asort/arsort正确处理我的代码。我最初使用sort/asort。当我打印_r时,数组显示为排序,然后我转到"createtable"函数,它只是按索引顺序打印值。有什么想法吗?

我的主文件中的代码段

//Sorts Array by value [Ascending] 
asort($songArray);
print_r($songArray);
//Creates table [See inc_func.php]
CreateTable ($songArray); 

参考函数

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>'; 
}  

谢谢。

对数组进行排序不会改变键,只会重新排序

然后,显示代码按数字顺序迭代数组,因此忽略该顺序。

相反,使用foreach循环:

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>';
}