0

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
        )

)

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
2
  • to get the table in one loop i think array needs some adjustments first. Commented Mar 3, 2011 at 19:53
  • bhu1st - what sort of adjustments? I don't have too much control over how this array is created. Commented Mar 3, 2011 at 20:14

7 Answers 7

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Hmm, I tried this and it still seems to print out the data in rows rather than columns. Quite possible I did something wrong though.
You are right...I was in a hurry. I updated the code to, hopefully, do what is needed.
1

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

1 Comment

Thanks, this works. Easy to tweak to use my array. I'm going to continue to refine but this is a great start.
1

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>";

1 Comment

refine it and make it clean.. i myself got some neat ideas from @Kevin Peno 's code. cheers!
0

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.

2 Comments

I've used datatables a bit for another project and was actually thinking of using it here. But I don't think that necessarily solves my problem of having each array set display in a column. In the datatables example, it'd be as if I wanted to put Rendering Engine, Browser, etc in their own column on the left. Does that make sense?
It does make sense. You're essentially looking for a pivot table...it ain't pretty with PHP/MySQL....
0

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>

Comments

-1

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

1 Comment

I was thinking that'd be the way to go, but I'm not familiar with the syntax to do this.
-1

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

2 Comments

He needs the table to show in columns per entry, not rows. Your method shows in rows per entry. CSS is pretty lacking when styling tables effectively (not to mention across platforms).
This is the general way I want to construct the table, but I need to flip the axes so the Date, Type, Minutes are all in a column, then each set of data in its own column. That's where I'm having trouble.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.