PHP如何在任何索引处添加到数组中


PHP How to add to an array at any index?

你好,我大约8天前刚开始学习PHP。我正试图从SQL表中加载注释,并根据它们的ID将它们按顺序排列。要做到这一点,我想使用一个数组,并将注释ID添加到索引中,这样它就可以按顺序排列了。

EX:(我认为这不是正确的代码)

while loop through SQL table{
   array[3] = This is comment 3.
   array[1] = This is comment 1.
   array[0] = This is comment 0.
   array[2] = This is comment 2.
}

正如你所看到的,它只是根据索引将注释按正确的顺序排列。我该如何在PHP中做到这一点?

以下是我到目前为止所拥有的,但它不起作用:

$return = "";
    $array = array();
    $lowers = 0;

    $res2 = mysql_query("SELECT * from `".Mod::$id."_comments`");
    if($res2){
        while($row = mysql_fetch_assoc($res2)){
            if($row['id'] < $lowers){
                $lowers = $row['id'];
            }
            $name = $row['id'] . "_delete";
            $array[$row['id']] = "<div class='"caption'"><hr><h5>"
            . getUserByUUID($row['uuid']) . " (" .  date('m/d/Y', $row['timestamp']) . ") <input type='"button'" name='"" . $name .
            "'" id='"" . $name . "'" value='"Delete'" onClick='"CALLJAVASCRIPTFUNCTIONHERE()'" ></h5>
                    <figure class='"img-polaroid'">" . 
                    $row['comment'] . "</figure>
                </div>";//TODO CHANGE THE CALL JAVA SCRIPT FUNCTION TO THE PROPER FUNCTION!!!!!
            alert("ARRAY: " . $array[$row['id']]);//This is getting called but it does nothing.  Also I made a php function called alert that DOES work.
        }
    }

    for($loop = $lowers; $loop < (count($array) + $lowers); $loop++){
        alert("LOOP: " . $loop);
        $return = $return + $array[$loop];
    }
    return $return;
    for($loop = $lowers; $loop < (count($array) + $lowers); $loop++){
        alert("LOOP: " . $loop);
        $return = $return + $array[$loop];
    }
    return $return;

谢谢你的帮助。

伙计,你的方法完全错误。为什么不必要地循环和处理?

您可以在执行查询时使用ORDERBY子句来执行此操作。

如果您想按索引(键)对PHP数组进行排序,那么您要寻找的是一个名为ksort()的内置函数。

从PHP.net(上面的链接):按键对数组进行排序,保持键与数据的相关性。这主要适用于关联数组


如果您希望对数据库中返回的ID进行排序,只需将查询更改为:

"SELECT * from `".Mod::$id."_comments` ORDER BY `id` ASC" (DESC if you want the newest first)

您不需要整个代码,删除它并尝试这个答案中的代码,并在需要的地方更改值,不要忘记将YourTableName更改为您的实际表名。它将要做的是选择每一件事,并根据他们的id订购结果。谢谢,

$res2 = mysql_query("SELECT * from YourTableName ORDER BY id ASC");
//Change YourTableName to your actual table name
  if($res2){
        while($row = mysql_fetch_assoc($res2)){
            echo $row['id'].'  :'.$row['comment'].'<br/>';
        }
        }