我的代码似乎不能正确使用asort/arsort。我最初使用的是sort/asort。当我创建数组时,数组显示为已排序,然后我转到我的“print_r”函数,它只按索引顺序打印值。知道是怎么回事吗?
我的主文件中的代码段
//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>';
} 谢谢。
发布于 2015-11-30 23:09:18
对数组进行排序不会改变键,只是对它们重新排序
然后,您的显示代码按数字顺序迭代数组,因此顺序将被忽略。
相反,使用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>';
} https://stackoverflow.com/questions/34001585
复制相似问题