dsg435665475 2016-09-01 17:32
浏览 49
已采纳

for循环使用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

  • 写回答

4条回答 默认 最新

  • duan1979768678 2016-09-01 18:03
    关注
    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
                    )
    
            )
    
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)