【问题标题】:asort/arsort issues with my array, arises on table creation我的数组的 asort/arsort 问题出现在创建表时
【发布时间】:2016-03-04 06:21:31
【问题描述】:

我似乎无法让 asort/arsort 与我的代码一起正常工作。我最初使用的是 sort/asort。当我 print_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>'; 
}  

谢谢。

【问题讨论】:

    标签: php arrays asort


    【解决方案1】:

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

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

    改为使用 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>';
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-05
      • 1970-01-01
      • 2018-10-23
      • 1970-01-01
      • 2016-04-11
      • 1970-01-01
      相关资源
      最近更新 更多