Php 有没有办法像这样从MySQL解析JSON
我想从服务器创建一个PHP API,将JSON解析为Android 但没关系 主要的问题是我如何编写代码 这是我的PHP代码Php 有没有办法像这样从MySQL解析JSON,php,json,mysqli,Php,Json,Mysqli,我想从服务器创建一个PHP API,将JSON解析为Android 但没关系 主要的问题是我如何编写代码 这是我的PHP代码 <?php include 'includes/conn.php'; $sql = "SELECT * FROM positions ORDER BY priority ASC"; $res = array(); $query = $conn->query($sql); while($row = $query->
<?php
include 'includes/conn.php';
$sql = "SELECT * FROM positions ORDER BY priority ASC";
$res = array();
$query = $conn->query($sql);
while($row = $query->fetch_assoc()){
$csql = "SELECT * FROM candidates WHERE position_id='".$row['id']."'";
$cquery = $conn->query($csql);
$cs = array(
'pos_id' => $row['id'],
'pos_des' => $row['description'],
'max_votes' => $row['max_vote']);
while($crow = $cquery->fetch_assoc()){
$fe = array(
'candidates' => array(
'id' => $crow['id'],
'pos_id' => $crow['position_id'],
'firstname' => $crow['firstname'],
'lastname' => $crow['lastname'],
'photo' => $crow['photo'],
'platform' => $crow['platform']
array_push($cs,fe);
)
);
}
array_push($res,$cs);
}
echo json_encode($res);
?>
我想要这个结果
[{
"pos_id": "1",
"pos_des": "Reprisentative",
"max_votes": "4",
"candidates": [{
"id": "1",
"pos_id": "1",
"firstname": "G-9-JAY",
"lastname": "MCARTHUR",
"photo": "",
"platform": ""
}, {
"id": "2",
"pos_id": "1",
"firstname": "G-10-JOHN",
"lastname": "MARTIN",
"photo": "",
"platform": ""
}, {
"id": "5",
"pos_id": "1",
"firstname": "GRADE 7",
"lastname": "Lang ya",
"photo": "",
"platform": ""
}]
},
{
"pos_id": "2",
"pos_des": "President",
"max_votes": "1",
"candidates": [{
"id": "3",
"pos_id": "2",
"firstname": "User",
"lastname": "Name",
"photo": "",
"platform": ""
}, {
"id": "4",
"pos_id": "2",
"firstname": "TEST",
"lastname": "USER",
"photo": "",
"platform": ""
}]
}
]
小结:我希望用户输入他/她分配给职位的职位id,例如,MARTIN是一位竞选总统,因此MARTIN应该显示在总统职位上
如何实现这一点?您应该使用
$cs['candidates']
,而不是创建一个单独的数组,将候选者
作为每个候选者的键
$cs = array(
'pos_id' => $row['id'],
'pos_des' => $row['description'],
'max_votes' => $row['max_vote'],
'candidates' => array());
while($crow = $cquery->fetch_assoc()){
$cs['candidates'][] = array(
'id' => $crow['id'],
'pos_id' => $crow['position_id'],
'firstname' => $crow['firstname'],
'lastname' => $crow['lastname'],
'photo' => $crow['photo'],
'platform' => $crow['platform']
);
}
您应该使用
$cs['candidates']
,而不是创建一个单独的数组,其中candidates
作为每个候选项的键
$cs = array(
'pos_id' => $row['id'],
'pos_des' => $row['description'],
'max_votes' => $row['max_vote'],
'candidates' => array());
while($crow = $cquery->fetch_assoc()){
$cs['candidates'][] = array(
'id' => $crow['id'],
'pos_id' => $crow['position_id'],
'firstname' => $crow['firstname'],
'lastname' => $crow['lastname'],
'photo' => $crow['photo'],
'platform' => $crow['platform']
);
}
. 错误:语法错误,第23I行中意外的“候选者”(T_常量_封装的_字符串),应为“)”缺少逗号。。错误:语法错误,第23I行中意外的“候选者”(T_常量_封装的_字符串),应为“)”缺少逗号。