猿问

来自 sql 数据库的 json_encode 结果

数据库:


ID  str域

1   x.com

2   y.com

3   z.com

$domainSettings = array();

$db_domainList = DB::get("SELECT strDomain FROM domains ORDER BY id ASC;");

foreach($db_domainList as $row) {

    $domainSettings = array($row->strDomain);

}

$result = array('allowedDomains' => $domainSettings);

echo json_encode($result, JSON_FORCE_OBJECT);

当前输出:{"allowedDomains":{"0":"x.com"}}


我需要类似于这样的输出:{"allowedDomains":"x.com","y.com","z.com"}


输出echo json_encode($db_domainList);:


[{"strDomain":"x.com"},{"strDomain":"z.com"},{"strDomain":"y.com"}]


慕无忌1623718
浏览 155回答 2
2回答

慕田峪9158850

如果考虑到所需的输出无效,我正确理解了您的问题,那么这段代码应该可以解决问题。$db_domainList = DB::get("SELECT strDomain FROM domains ORDER BY id ASC;");$domainSettings = []; //Just incase $db_domainList is emptyforeach($db_domainList as $row) {    $domainSettings[] = $row->strDomain;}$result = array('allowedDomains' => $domainSettings);echo json_encode($result);请注意,我已删除JSON_FORCE_OBJECT标志,因为您要求包含和数组的输出。上面代码的输出应该看起来像这样,这与您要查找的内容非常接近。{    "allowedDomains": [        "x.com",        "y.com",        "z.com"    ]}

慕姐4208626

如果我没有误解你的要求,那么你可以这样做 -$db_domainList = DB::get("SELECT strDomain FROM domains ORDER BY id ASC;");foreach($db_domainList as $row) {    $domainSettings[] = $row->strDomain;}$result = array('allowedDomains' => implode(',',$domainSettings));echo json_encode($result, JSON_FORCE_OBJECT);
随时随地看视频慕课网APP
我要回答