请提供PHP mysqli_fetch_assoc帮助

请提供PHP mysqli_fetch_assoc帮助,php,arrays,database,while-loop,Php,Arrays,Database,While Loop,这可能已经被问到和回答了,但我找不到一个适合我正在尝试做的事情的解决方案。我需要确定由mysqli_fetch_assoc$result创建的关联数组的结尾。我的密码是: $query = "SELECT * " . "FROM songs;"; $result = mysqli_query($connection, $query); $number = mysqli_num_rows($result); while($row = mysqli_fetch_assoc($r

这可能已经被问到和回答了,但我找不到一个适合我正在尝试做的事情的解决方案。我需要确定由mysqli_fetch_assoc$result创建的关联数组的结尾。我的密码是:

$query = "SELECT * " .
         "FROM songs;";

$result = mysqli_query($connection, $query);
$number = mysqli_num_rows($result);

while($row = mysqli_fetch_assoc($result)){

    if($number !== 0){
        echo "{'title':'" .$row['song_name'] .
             "'file':'" . $row['song_path'] . "'},<br /><br />"; 
    } else {
        echo "{'title':'" .$row['song_name'] .
             "','file':'" . $row['song_path'] . "'}<br /><br />"; 
    }
    $number--;


}
有人请告诉我我做错了什么。我想做的是回显if语句的第一部分,如果该行是数组中的最后一行,我想回显else,在两个break标记之前的末尾不带逗号。它返回数据库中的所有行,但如果逗号是数组的结尾,我就无法去掉它。我和这件事玩得很开心。我知道这可能很简单,但我对PHP还不熟悉,这让我陷入了困境。请帮忙

你能试试这个吗

  $i=1;
  while($row = mysqli_fetch_assoc($result)){    
        $comma =",";    
        if($i==$number){
            $comma ="";
        }   
        echo "{'title':'" .$row['song_name'] .
        "'file':'" . $row['song_path'] . "'}".$comma."<br /><br />";
        $i++;

  }
你应该试试

 ... 
 if($number > 1){
 ...
或者你可以按你的意愿去做

  ...
  $json = '';
  while($row = mysqli_fetch_assoc($result)){

      $json .=  "{'title':'" .$row['song_name'] .
         "'file':'" . $row['song_path'] . "'},"; 
  }

  if(strlen($json) > 0)
       $json = substr($json,0, strlen($json)-1);

  echo $json;

在一行结束后使用$number,以便在处理完所有行后,$number将等于0。因此,您需要做的就是将$number-放在所有if子句之前

 while($row = mysqli_fetch_assoc($result)){
     $number--;//move to here
     if($number !== 0){
         echo "{'title':'" .$row['song_name'] .
              "'file':'" . $row['song_path'] . "'},<br /><br />"; 
     } else {
         echo "{'title':'" .$row['song_name'] .
              "','file':'" . $row['song_path'] . "'}<br /><br />"; 
     }
     //$number--; moved up


  }
现在应该可以了!!: