Donald Donald - 3 months ago 12
MySQL Question

for loop to display the array in the correct format using php

I am fetching the records from the database using the following code snippet:

if($pdo)
{
$stmt = $pdo->query('SELECT ID,Province,City,Position,Locale FROM jobs');
$result=$stmt->fetchAll(PDO::FETCH_ASSOC);
print("<pre>".print_r($result,true)."</pre>");
}


I am getting the array :

I would like to retrieve the values using for each loop and display on the website:

Province name
city name:
position name1:
position name 2:
province name
city name:
Position name 3:
Position name 4:


I Have written the code :

<?foreach($result as $key=>$val):?>
<div class='r-wr'>
<h2 class="region-heading"><?=$key?></h2>
<?foreach($val as $city=>$result):?>
<div class='c-wr'>
<h3 class="city-heading"><?=$city?></h3>
<?foreach($result as $pos_key=>$position):?>
<div class="pstn-btn" position-id="<?=$pos_key;?>"><?=$position;?></div><br>
<?endforeach;?>
</div>
<?endforeach;?>
</div>
<?endforeach;?>


can anyone please help me how to write the for each loop to get the record values.

Thanks

Answer
foreach($result as $key=>$val){
    $res[$val['Province']][$val['City']][$val['ID']] = $val['Position'];
}

The output is:

Array
(
    [BC] => Array
        (
            [Winnipeg] => Array
                (
                    [1] => Licensed Technician - Body Technician
                )

        )

    [Prairies] => Array
        (
            [Winnipeg] => Array
                (
                    [2] => Licensed Technician - Body Technician
                )

            [Edmonton] => Array
                (
                    [3] => Tire Technician
                )

        )

    [Ontario] => Array
        (
            [Regional Support Centre (Mississauga)] => Array
                (
                    [4] => Customer Service Representative
                    [5] => Payroll and Benefits Administrator
                )

            [Mississauga] => Array
                (
                    [6] => Shunt-Delivery Driver
                    [7] => Technician
                )

        )

)