0

我正在尝试通过php从数据库中检索多个值到我在eclipse中的android java。除了我需要的之外,我正在设法获得所有 json 数组的变体。

我的数据库是:

**Aircraft**        **Status**
  A870_870              1
  A870_871              1
  A870_872              1
  A870_873              1 
  A870_874              1 
  A870_875              1
  A870_876              2
  A870_877              1
  A870_878              2
  A870_879              2 
  A870_880              2
  A870_881              0
  A870_882              0
  A870_883              0
  A870_884              0
  A870_885              0

我需要的格式,以便我的 android 应用程序读取它是:

    {"A70_870":"1","A70_871":"1","A70_872":"1","A70_873":"1","A70_874":"1",
"A70_875":"1","A70_876":"2","A70_877":"1","A70_879":"2","A70_878":"2",
"A70_880":"2","A70_881":"0","A70_882":"0","A70_883":"0","A70_884":"0",
"A70_885":"0"}

我一直在尝试不同的“while”循环和各种其他变体,并设法获得各种组合,除了我需要的组合。肯定有办法……?

我最接近的 PHP 尝试如下:

<?php
$con = mysqli_connect("localhost","root","", "mytestdatabase"); 

 if (mysqli_connect_errno()) { 
     echo 'Database connection error: ' . mysqli_connect_error(); 
     exit(); 
     } 

$userdetails = mysqli_query($con, "SELECT *FROM aircraft_status"); 

$row = mysqli_fetch_row($userdetails) ;

$result_data = array(

    'A70_870'=>$row[1],
    'A70_871'=>$row[1],
    'A70_872'=>$row[1],
    'A70_873'=>$row[1],
    'A70_874'=>$row[1],
    'A70_875'=>$row[1],
    'A70_876'=>$row[1],
    'A70_877'=>$row[1],
    'A70_879'=>$row[1],
    'A70_878'=>$row[1],
    'A70_880'=>$row[1],
    'A70_881'=>$row[1],
    'A70_882'=>$row[1],
    'A70_883'=>$row[1],
    'A70_884'=>$row[1],
    'A70_885'=>$row[1],);

echo json_encode($result_data);
?>

它提供了正确的格式,但显然只读取第 1 行。我无法访问 3、5、7 等。

如果有人能在这方面帮助我,那就太好了!!:) 我敢肯定这很简单,我做得不对……

4

1 回答 1

0

我可能遗漏了一些东西,但它不仅仅是将结果提取包装在一个 while 循环中:

$userdetails = mysqli_query($con, "SELECT *FROM aircraft_status"); 

$result_data = array();

if ($userdetails) {
  while($row = mysql_fetch_array($userdetails)) {
    // $row[0] being aircraft and $row[1] being status
    array_push($result_data , $row[0], $row[1]);
  }

}
else {
  echo mysql_error();
}

echo json_encode($result_data);

我的 PHP 很生锈,所以可能需要调整。希望这能让你上路。

于 2013-10-10T12:05:50.657 回答