在html表中回显多维数组

时间:2016-01-04 02:10:02

标签: php html arrays

我有一个具有相同值的多维数组,

[documents] => Array
(
    [0] => Array
            (
                [doc_id] => 3
                [doc_type] => driving_licence                   
                [expiry_date] => 2015-11-26
                [added_date] => 2015-11-16
            )

    [1] => Array
            (
                [doc_id] => 3
                [doc_type] => driving_licence
                [expiry_date] => 2015-11-26
                [added_date] => 2015-11-16
            )

)

所以现在我需要在单个<tr>的html表中回显这个数组。

这是我尝试的方式:

foreach ($userData as $key => $value) {
    $i=0; 
    foreach ($value['documents'] as $k => $v) {
        $i++; 
        $html  = "<tr>\n"; 
        $html .= " <td class='center'>{$i}</td>";
        $html .= " <td>{$v['doc_type']}</td>";
        $html .= " <td>{$v['expiry_date']}</td>";
        $html .= " <td>{$v['added_date']}</td>";
        $html .= "</tr>\n"; 

        echo $html; 
    }
}

但它的重复表<tr>具有相同的值。

有谁能告诉我如何避免这种情况? 谢谢。

2 个答案:

答案 0 :(得分:1)

As requested,这是一个例子。

$userData = $input = array_map("unserialize", array_unique(array_map("serialize", $userData)));

foreach ($userData as $key => $value) {
    $i=0; 
    foreach ($value['documents'] as $k => $v) {
        $i++; 
        $html  = "<tr>\n"; 
        $html .= " <td class='center'>{$i}</td>";
        $html .= " <td>{$v['doc_type']}</td>";
        $html .= " <td>{$v['expiry_date']}</td>";
        $html .= " <td>{$v['added_date']}</td>";
        $html .= "</tr>\n"; 

        echo $html; 
    }
}

这将为您提供一个 1 <tr>行的表格。

答案 1 :(得分:0)

这就是我想做你想做的事情:

 $movies = array 
   (
      array('Office Space' , 'Comedy' , 'Mike Judge' ),
      array('Matrix' , 'Action' , 'Andy / Larry Wachowski' ),
      array('Lost In Translation' , 'Comedy / Drama' , 'Sofia Coppola' ),
      array('A Beautiful Mind' , 'Drama' , 'Ron Howard' ),
      array('Napoleon Dynamite' , 'Comedy' , 'Jared Hess' )
   );

   echo "<table border=\\"1\\">";
   echo "<tr><th>Movies</th><th>Genre</th><th>Director</th></tr>";
   for ( $row = 0; $row < count($movies); $row++ )
   {
      echo "<tr><td>";
      for ( $column = 0; $column < count($movies); $column++ )
      {
         echo $movies[$row][$column] ;
      }
      echo "<td></tr>";
   }