开发者

Display PHP multidimensional array in html table with each subarray in a column

I'm sure there's a fairly easy way to do this. I have an the following data in an array:

Array
(
    [ActivityDiaryEntry] => Array
        (
            [date] => 2011-03-03
            [type] => Walking
            [minutes] => 60
        )

)
Array
(
    [ActivityDiaryEntry] => Array
        (
            [date] => 2011-03-02
            [type] => Walking
            [minutes] => 22
        )

)
Array
(
    [ActivityDiaryEntry] => Array
        (
            [date] => 2011-03-01
            [type] => Biking
            [minutes] => 45
   开发者_如何学C     )

)

I'm not too skilled at PHP, but I know how to display this data by row to display as <tr><td>[date]</td><td>[type]</td><td>[minutes]</td></tr>. But I'd like to have the data display in columns like this:

2011-03-01 | 2011-03-02 | 2011-03-03
------------------------------------
Biking     | Walking    | Walking
------------------------------------
45         | 22         | 60


I didn't test this, but it should work. It should serve as an example of what needs to be done. I tried to write this to limit the number of foreach loops used. If I reordered the data first and then performed the takes, I'd of needed 4 foreach loops. The benefit to this method is that you don't need to update the code if more columns are added, so long as all records have the same number of columns.

<?php
// Your list of records
$records = array(
    array( "key1" => "value", "key2" => "value", "key3" => "value" ),
    array( "key1" => "value", "key2" => "value", "key3" => "value" ),
    array( "key1" => "value", "key2" => "value", "key3" => "value" )
);

// Create an array to store the values of each row based on number of columns in first value
$rows = array_fill( 0, count( $records[0] ), "" );
$keys = array_keys( $records[0] );

// Create a column for each record in it's respective row.
foreach( $records as $k => $record )
    for( $i=0, $max=count( $rows ); $i < $max; $i++ )
        $rows[ $i ] .= "<td>".$record[ $keys[ $i ] ]."</td>";

// Turn each row in our array into an html table row.
print "<tr>".implode( "</tr><tr>", $rows )."</tr>";

Here's the code test: http://codepad.org/SSS8S2eU


A little ugly but works :')

$a[0] = array('ActivityDiaryEntry' => array("date" => "2011-03-03", "type"=> "Walking", "minutes" => 60));
$a[1] = array('ActivityDiaryEntry' => array("date" => "2011-03-03", "type"=> "Walking", "minutes" => 22));
$a[2] = array('ActivityDiaryEntry' => array("date" => "2011-03-03", "type"=> "Biking", "minutes" => 42));

$keys = array_keys($a[0]["ActivityDiaryEntry"]);

echo '<table>';
for($c = 0; $c < count($a); $c++) {
    echo '<tr>';
        for($i = 0; $i < count($a[$c]['ActivityDiaryEntry']); $i++) {
            echo '<td>' . $a[$i]['ActivityDiaryEntry'][$keys[$c]] . '</td>';
        }
    echo '</tr>';       
}
echo '</table>';

http://codepad.org/5Tuk8x3Q


This code works if i am not wrong defining the array, but i suggest you play with all the options provided here and find a better solution.

$data = array (
array (
   'ActivityDiaryEntry' => array
        (
            'date' => "2011-03-03",
            'type' => "Walking",
            'minutes' => 60
        )
    ),
    array (
    'ActivityDiaryEntry' => array
        (
            'date' => "2011-03-02",
            'type' => Walking,
            'minutes' => 22
        ) ),
array (
    'ActivityDiaryEntry' => array
        (
            'date' => "2011-03-01",
            'type' => Biking,
            'minutes' => 45
        )
        )
);    

echo "<table>";
$i = 0;

foreach ($data as $key => $val) {
echo "<tr>";
    foreach ($data as $kk => $vv){


    if ($i==0) {
        echo "<td>". $vv['ActivityDiaryEntry']['date'] ."</td>";    
    }else if ($i == 1){
        echo "<td>". $vv['ActivityDiaryEntry']['type'] ."</td>";    
    }else if ($i == 2){
        echo "<td>". $vv['ActivityDiaryEntry']['minutes'] ."</td>"; 
    }


    }

echo "</tr>";
$i++;
}

echo "</table>";


This would be a great candidate for DataTables, which is actually Javascript that I use to display my results generated on the back end by PHP. It's a full-blown javascript grid system that adds a ton of features to standard HTML table outputs. To make it work you would:

  1. Get your results as shown and output as a json_encoded string (i.e, echo json_encode($array) I do this in a separate file so it outputs clean text to the screen.
  2. On the page to display the table, setup a "dummy table"
  3. Setup Datatables in the same page as the dummy table like this:

    $(document).ready(function() {
        $('#replace').dataTable( {
            "bProcessing": true,
            "sAjaxSource": 'file.php'
        } );
    } );
    
  4. Set values for sorting, filtering, paging, etc. per the tutorial.

Datatables gives you so much more power than just a standard HTML table, and you're already 90% of the way there with the data. It's so much more user friendly than just jamming stuff on the screen.


Before transposing your data (converting columns to rows), you must reduce the depth/complexity by removing the unusable first level and generate an indexed array of what is left.

Then iterate the first array in the new, simplified data structure and extract column data. Each column (there are three) will be displayed in its own table row using a flexible implode()ing technique.

Code: (Demo)

$subarrays = array_column($array, "ActivityDiaryEntry");

echo '<table>';
foreach ($subarrays[0] as $column => $notUsed) {
    echo '<tr><td>' , implode('</td><td>', array_column($subarrays, $column)) , '</td></tr>';
}
echo '</table>';

Output:

<table>
    <tr>
        <td>2011-03-03</td>
        <td>2011-03-03</td>
        <td>2011-03-03</td>
    </tr>
    <tr>
        <td>Walking</td>
        <td>Walking</td>
        <td>Biking</td>
    </tr>
    <tr>
        <td>60</td>
        <td>22</td>
        <td>42</td>
    </tr>
</table>


You could write a for loop for each field, displaying one row in each loop.


The Javascript answer below might be a good way to do it, but I would suggest using PHP and tables if you are not completely comfortable using Javascript in your applications. It is also good PHP practice.

If I were you, I'd use code like this, and css properties to format the table how you'd like.

  echo '<table>';
  echo '<tr><td>Date</td><td>Type</td><td>Minutes</td></tr>';

  foreach ($array as $entry){
      echo '<tr>';
      echo '<td>'.$entry['date'].'</td>';
      echo '<td>'.$entry['type'].'</td>';
      echo '<td>'.$entry['minutes'].'</td>';
      echo '</tr>';
  }

  echo '</table>';

You can use stuff like this to edit your tables display, also check out http://www.w3schools.com/css/css_table.asp

echo '<tr style="border-bottom: 1px solid black;"></tr>';

cheers

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜