以结构化方式回应复杂数组

时间:2014-08-19 04:57:41

标签: php

$hours = [
  'Mon' => ['07:30 AM' => '04:00 PM'],
  'Tue' => ['07:30 AM' => '04:00 PM'],
  'Wed' => ['07:30 AM' => '04:00 PM'],
  'Thu' => ['07:30 AM' => '04:00 PM'],
  'Fri' => ['07:30 AM' => '04:00 PM'],
  'Sat' => ['10:00 AM' => '04:00 PM'],
  'Sun' => ['closed']
];

我无法回应上述数组,结构如下:

周一 - 上午7:30 - 下午4:00

星期二 - 上午7:30 - 下午4:00

...

在某种类型的结构化方式中,无论是在表格中,还是在我可以使用CSS构建的div中。

2 个答案:

答案 0 :(得分:1)

你可以试试这个:

<?php 
$hours = array(
'Mon' => array('07:30 AM' => '04:00 PM'),
'Tue' => array('07:30 AM' => '04:00 PM'),
'Wed' => array('07:30 AM' => '04:00 PM'),
'Thu' => array('07:30 AM' => '04:00 PM'),
'Fri' => array('07:30 AM' => '04:00 PM'),
'Sat' => array('10:00 AM' => '04:00 PM'),
'Sun' => array('closed')
); 


foreach ($hours as $key=>$val){
    $html='';
    $html.= $key."   ";
    if(is_array($val)){
        foreach($val as $key1=>$val1){
            if($key1 == 0){
                $html.= $val1.'<br>';
            }else{
            $html.= $key1."   ".$val1.'<br>';

        }
    }}else{
        $html.= $val.'<br>';
    }
    echo $html;
}

?>

数组结构我已经改变了,你可以改变它。

答案 1 :(得分:0)

此代码可以帮助您,它在表格中回显数组

$hours = [
  'Mon' => ['07:30 AM' => '04:00 PM'],
  'Tue' => ['07:30 AM' => '04:00 PM'],
  'Wed' => ['07:30 AM' => '04:00 PM'],
  'Thu' => ['07:30 AM' => '04:00 PM'],
  'Fri' => ['07:30 AM' => '04:00 PM'],
  'Sat' => ['10:00 AM' => '04:00 PM'],
  'Sun' => ['closed']
];


echo "<table>";
foreach($hours as $key => $value)
{
   echo "<tr>";
   echo "<td>" . $key . "</td>";
   foreach($value as $key2 => $value2)
   {
       echo "<td>" . (($key2!=0)?$key2:'') . "</td>";
       echo "<td>" . $value2 . "</td>";
   }
   echo "</tr>";
}
echo "</table>";