【问题标题】:Php mysql_fetch add me the row number at the begining of each rowphp mysql fetch 在每行的开头添加我的行号
【发布时间】:2015-03-20 23:02:25
【问题描述】:

这是我的 php 代码:

 $query = Select * from tablename;
 $result = mysql_query($query) or die((mysql_error()));
 $count = 0;
 if (mysql_num_rows($result) > 0){


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


      $json_output[$count]=$row;

      $count ++;

   }


}


 $output = json_encode($json_output);

 $output = str_replace('[{', '{', $output);
 $output = str_replace('}]', '}', $output);

 echo $output;

这是我的 php 输出的一部分:

 {"0":{"0":"2","Gi_Id":"2","1":"sample_name.jpg","Gi_nome_file":"sample_name.jpg","2":"sample_name","Gi_Pseudonimo":"s. name","3":"sample name","

如您所见,有标签“0”、“1”、“2”等表示我的 sql 表的列号(“0”代表 Gi_Id,“1”代表 Gi_nome_file 等)。 为什么会有这个重复项? 可能我可以忽略重复的单个单元格值来管理此输出,但我想不知道如何解决这个问题。

我认为问题在于我的这行代码:

 $json_output[$count]=$row;

但我没有找到其他方法来获取我的所有表格数据。

有什么建议吗?

编辑

使用 mysql_fetch_assoc 我没有重复但保留每行开头的数字,我的输出如下:

{"0":{"Gi_Id":"2","Gi_nome_file":"sample_name.jpg","Gi_Pseudonimo":"s. name", 

对于第 2 行,我有:

{"1":{"Gi_Id":"3","Gi_nome_file":"sample_name.jpg","Gi_Pseudonimo":"s. name", 

对于第 3 行,我有:

{"2":{"Gi_Id":"4","Gi_nome_file":"sample_name.jpg","Gi_Pseudonimo":"s. name", 

...

对于我拥有的行号 n:

{"n":{"Gi_Id":"n+1","Gi_nome_file":"sample_name.jpg","Gi_Pseudonimo":"s. name", 

等 我想删除 {"0": , {"1": ,{"2":, {"3": 在每一行的开头,我该怎么做?

【问题讨论】:

  • 阅读 mysql_fetch_array() 返回的内容...php.net/manual/en/function.mysql-fetch-array.php
  • 如何使用 mysql_fetch_array( ) 来解决我的问题?
  • 您阅读了手册页并看到了它返回的内容并看到了 See Also 链接?
  • mysql_fetch_assoc,解决我的重复问题。现在我会尝试删除 {"0": , {"1" ecc 指示 $count 值($json_output 数组键)
  • 您的预期输出是什么?你有你希望它看起来像的示例 json 吗?

标签: php mysql sql json


【解决方案1】:

我解决了我的问题:

这是解决方案:

 $result = mysql_query($query) or die((mysql_error()));

$json_output = 数组(); $count = 0;

$response["Prova"] = array(); if (mysql_num_rows($result) > 0){

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


    $json_output[$count]=$row;

    // push single rating into final response array


    $count ++;

}

array_push($response["Prova"], $json_output);


}

//alla fine aggiungo il tag di successo
$json_output["success"] = 1;

$output = json_encode(array($response));
//rimuovo le parentesi graffe per far si che non mi dia problemi con il json di android
$output = str_replace('[{', '{', $output);
$output = str_replace('}]', '}', $output);

echo $output;

【讨论】:

    猜你喜欢
    • 2017-08-17
    • 2011-04-15
    • 1970-01-01
    • 1970-01-01
    • 2013-08-06
    • 2013-06-28
    • 2012-02-09
    • 1970-01-01
    相关资源
    最近更新 更多