MySQL选择结果返回为数组中的数组

时间:2018-12-22 11:21:29

标签: php json mysqli

我正在尝试从mysql数据库中选择结果作为array中的一个数组。

MariaDB 10.3

$fetch = $GLOBALS['mysqli']->query("SELECT id, name, (SELECT JSON_ARRAY(JSON_OBJECT('code',(SELECT code FROM zip WHERE id = zip)),JSON_OBJECT('name',(SELECT name FROM zip WHERE id  = zip)))) AS zip FROM orders WHERE id = '188'");

$rows = array();
$r = mysqli_fetch_assoc($fetch);
$rows['PLZ'] = $r;

print_r($rows);

我得到以下结果

Array ( [PLZ] => Array ( [id] => 188 [name] => Boban [zip] => [{"code": "1140"}, {"name": "Penzing"}] ) ) 

我期望的结果是

Array ( [PLZ] => Array ( [id] => 188 [name] => Boban [zip] =>  Array ( [code] => 1140 [name] Penzing) ) ) 

有人可以帮我吗?

已解决

$fetch = $GLOBALS['mysqli']->query("SELECT id, name, (SELECT JSON_OBJECT('code',(SELECT code FROM zip WHERE id = zip),'name',(SELECT name FROM zip WHERE id  = zip))) AS zip FROM orders WHERE id = '188'");

$rows = array();
$r = mysqli_fetch_assoc($fetch);
$rows['PLZ'] = $r;

foreach ($rows as &$row) {
    $row['zip'] = json_decode($row['zip'], true);
}

print_r($rows);

我在带有选项a)的Lajos Veres的帮助下解决了问题,而sql几乎没有变化

1 个答案:

答案 0 :(得分:0)

a) 我认为,假设您要保留此数组结构,可能是将结果对象从json转换为php数组的最简单方法:

SELECT
    id,
    name,
    (SELECT code FROM zip WHERE id = zip) as code,
    (SELECT name FROM zip WHERE id = zip) as zip
FROM
    orders
WHERE
    id = '188'

b) 否则,我将重新处理查询以在不同的字段中返回所需的数据:

{{1}}