Home > Software engineering >  PHP PDO iterating Associative Array returning errors
PHP PDO iterating Associative Array returning errors

Time:04-17

I need to Iterate through an Associative array that's being generated from PHP PDO.

PDO:

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

Array output:

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
        )

)

I have tried:

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

its returning errors:

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

Also tried nested loop:

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

CodePudding user response:

You're on the right path with the nested loop, but in the outer loop you don't need to worry about the key, only the inner loop:

<?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;
}

Outputs:

setting => site_title
setting_value => My Website

setting => site_desc
setting_value => Description of my website

setting => batch
setting_value => 2022-23
  • Related