Search code examples
phpmysqlarraysjson.net

json_encode result from sql database


Database:

id strDomain
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);

Current output: {"allowedDomains":{"0":"x.com"}}

I need output similar to this: {"allowedDomains":"x.com","y.com","z.com"}

Output of echo json_encode($db_domainList);:

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

Solution

  • If I understand your question correctly considering the needed output is invalid, this code should do the trick.

    $db_domainList = DB::get("SELECT strDomain FROM domains ORDER BY id ASC;");
    
    $domainSettings = []; //Just incase $db_domainList is empty
    
    foreach($db_domainList as $row) {
        $domainSettings[] = $row->strDomain;
    }
    
    $result = array('allowedDomains' => $domainSettings);
    echo json_encode($result);
    

    Note that I have removed JSON_FORCE_OBJECT flag since you are asking for an output that contains and array.

    The output of the above code should look like this which is very close to what you are looking for.

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