简体   繁体   English

从mysql检索数据返回3行相同的数据

[英]Retrieving of data from mysql returns the same for 3 rows

How do i encode this in json format? 我如何以json格式编码? I am receiving the same data in my 1st, 2nd and 3rd if i put 1st, while if i put "2nd"=>$row 1 , "3rd"=>$row 1 the same data as the 1st is being retrieved. 如果我把1st放在第一,第二和第三,我收到相同的数据,而如果我把“2nd”=> $ row 1 ,“3rd”=> $ row 1 ,则检索第一个相同的数据。 If i try to put in 3 it gives me a null. 如果我试图输入3它给我一个空。 Please someone help, Thanks. 请有人帮忙,谢谢。

Here is my php 这是我的PHP

$sql = "select
  n_name,
  shortcut,
  case
    when rank = 1 then '1st'
    when rank = 2 then '2nd'
    when rank = 3 then '3rd'
  end as rank
from
  team inner join nonsport on team.n_id = nonsport.n_id group by n_name order by n_name asc";                         

 $con = mysqli_connect($server_name,$mysql_user,$mysql_pass,$db_name); 

$result = mysqli_query($con,$sql);


 $response = array();
while($row=mysqli_fetch_array($result))
{
array_push($response, array("n_name"=>$row[0], "1st"=>$row[1], "2nd"=>$row[2], "3rd"=>$row[2]));
 }



echo json_encode (array("nresults"=>$response));

My expected output is 我的预期产量是

Example. 例。 Shortcut has a, b, c and they have rank a =1 b =2 c =3; 快捷方式有a,b,c,它们的等级a = 1 b = 2 c = 3;

Then 1st = a, 2nd = b, 3rd = c; 然后1st = a,2nd = b,3rd = c;

What im getting is 我得到的是什么

1st = a, 2nd = a, 3rd = a 1st = a,2nd = a,3rd = a

表

your query is returning 3 attributes for each row "n_name, shortcut, rank" and the rank will be "1st", "2nd", or "3rd", so you will not get the three ranks in a single row. 您的查询为每行返回3个属性“n_name,shortcut,rank”,排名将为“1st”,“2nd”或“3rd”,因此您不会在一行中获得三个排名。 I think you need to check the value of rank before assign it, as follow: 我认为你需要在分配之前检查排名的值,如下所示:

while($row=mysqli_fetch_array($result)){
    $array = [];
    $array["n_name"] = $row[0];

    if($row[1]=='a'){
        $array["1st"] = $row[1];
    } elseif($row[1]=='b'){
        $array["2nd"] = $row[1];
    } elseif($row[1]=='c'){
        $array["3rd"] = $row[1];
    }

    array_push($response, $array);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM