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条)

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向