在 JSON 字典中返回 Mysqli

Returning Mysqli in JSON Dict

我正在从 mysql 数据库中检索数据,并希望将其 return 作为 JSON 字典。

<?php
if($db->connect_errno > 0){
   die('Unable to connect to database [' . $db->connect_error . ']');
}

$sql = <<<SQL
SELECT tbldomainpricing.extension, tblpricing.msetupfee
FROM `tblpricing`
INNER JOIN tbldomainpricing ON tbldomainpricing.id = tblpricing.relid 
WHERE tblpricing.type = 'domainregister'
SQL;

if(!$result = $db->query($sql)){
    die('There was an error running the query [' . $db->error . ']');
}

$all_rows = array();

while($row = $result->fetch_assoc()) {
 $all_rows []= $row['extension'] . ":" . $row['msetupfee'];
}
header("Content-Type: application/json");
echo json_encode($all_rows);
?>

return :

{"extension":".com","msetupfee":"6.99"},{"extension":".net","msetupfee":"6.99"} ,

如何让 return 成为

{"com":"6.99"},{"net":"6.99"}

谢谢

听起来像你想要的:

while($row = $result->fetch_assoc()) {
 $all_rows[$row['extension']] = $row['msetupfee'];
}

参考u_mulder的评论,你可能还想要这个:

while($row = $result->fetch_assoc()) {
 $all_rows[][$row['extension']] = $row['msetupfee'];
}

我没有测试它,但你可能需要这样的东西:

while($row = $result->fetch_assoc()) {
 $all_rows[] = array($row['extension'], $row['msetupfee']);
}