PHP PDO 迭代关联数组返回错误

PHP PDO iterating Associative Array returning errors

我需要遍历从 PHP PDO 生成的关联数组。

PDO:

$stmt = $pdo->query("SELECT setting, setting_value FROM app_config")->fetchAll(PDO::FETCH_ASSOC);

数组输出:

Array
(
    [0] => Array
        (
            [setting] => site_title
            [setting_value] => My Website
        )

    [1] => Array
        (
            [setting] => site_desc
            [setting_value] => Description of my website
        )

    [2] => Array
        (
            [setting] => batch
            [setting_value] => 2022-23
        )

    [3] => Array
        (
            [setting] => session_start
            [setting_value] => 01-April-2022
        )

    [4] => Array
        (
            [setting] => session_end
            [setting_value] => 01-March-2023
        )

    [5] => Array
        (
            [setting] => site_mode
            [setting_value] => development
        )

    [6] => Array
        (
            [setting] => copyright
            [setting_value] => All rights reserved
        )

)

我试过了:

foreach ($stmt as $key => $value)
{
  echo "<p>$key = $value</p>";
}

其返回错误:

Warning: Array to string conversion in C:\xampp\htdocs\myweb\app\config\config.php on line 58 0 = Array

Warning: Array to string conversion in C:\xampp\htdocs\myweb\app\config\config.php on line 58 1 = Array

Warning: Array to string conversion in C:\xampp\htdocs\myweb\app\config\config.php on line 58 2 = Array

Warning: Array to string conversion in C:\xampp\htdocs\myweb\app\config\config.php on line 58 3 = Array

Warning: Array to string conversion in C:\xampp\htdocs\myweb\app\config\config.php on line 58 4 = Array

Warning: Array to string conversion in C:\xampp\htdocs\myweb\app\config\config.php on line 58 5 = Array

Warning: Array to string conversion in C:\xampp\htdocs\myweb\app\config\config.php on line 58 6 = Array

也试过嵌套循环:

foreach ($stmt as $key => $value) {
  foreach ($key as $result) {
      echo '<pre>'. $value .' : '. $result . '</pre>';
  }
}

您在嵌套循环的正确路径上,但在外循环中您无需担心密钥,只需担心内循环:

<?php

$data = [
    [
        'setting' => 'site_title',
        'setting_value' => 'My Website'
    ],
    [
        'setting' => 'site_desc',
        'setting_value' => 'Description of my website'
    ],
    [
        'setting' => 'batch',
        'setting_value' => '2022-23'
    ]
];

foreach ($data as $record) {
    foreach ($record as $key => $value) {
        echo $key . ' => ' . $value . PHP_EOL;
    }
    echo PHP_EOL;
}

输出:

setting => site_title
setting_value => My Website

setting => site_desc
setting_value => Description of my website

setting => batch
setting_value => 2022-23