PDO输出为JSON格式

时间:2018-09-17 14:06:22

标签: php json pdo

我这里有一些简单的PHP:

$root="../../";
include $root . 'config/config.php';
require $root . 'vendor/autoload.php';

$list = "SELECT words FROM random_words ORDER BY RAND() LIMIT 3";

$list1 = $pdo->query($list)->fetchAll(PDO::FETCH_COLUMN);
$list2 = $pdo->query($list)->fetchAll(PDO::FETCH_COLUMN);

我想遍历$list1的结果,并输出随机词以及来自list2的相应随机词,最后得到这种JSON输出

[{
  "id": 0,
  "random_combination": "scans.graduate"
}, {
  "id": 1,
  "random_combination": "apricot.dudley"
}, {
  "id": 2,
  "random_combination": "flushed.subscript"
}]

但是,我在解决如何实现目标方面遇到了麻烦。

我已经能够像这样拼凑一些东西:

$words = array();

for ($x = 0; $x <= 2; $x++) {

    $un1 = $list1[$x];
    $un2 = $list2[$x];
    $un3 = $un1 . "." . $un2;

    $words['output']['id'][] = $x;
    $words['output']['random_combination'][] = $un3;

    $output = json_encode($words);

}

print_r($words);

返回$ words的print_r:

Array
(
    [output] => Array
        (
            [id] => Array
                (
                    [0] => 0
                    [1] => 1
                    [2] => 2
                )

            [random_combination] => Array
                (
                    [0] => scans.graduate
                    [1] => apricot.dudley
                    [2] => flushed.subscript
                )

        )

)

但是,这与我想要获得的输出并不完全相同,但是我无法弄清楚得到我想要的东西的逻辑。

1 个答案:

答案 0 :(得分:1)

要使您的代码更通用,请使用foreach而不是for

foreach ($list1 as $k => $v) {
    $words['output'][] = [
        'id' => $k,
        'random_combination' => $v . '.' . $list2[$k], 
    ];
}

echo json_encode($words);