Question

I have a multidimensional array that looks like this:

Array(

[DETROIT] => Array
    (
        [NORTH] => 20.00%
        [SOUTH] => 30.00%
        [WEST] => 25.00%

    )

[CHICAGO] => Array
    (
        [NORTH] => 59.14%
        [SOUTH] => 12.94%
        [WEST] => 0.00%
        [EAST] => 34.60%
    )

 [NEW YORK] => Array
    (
        [WEST] => 38.00%
        [EAST] => 49.00%
    )

[DALLAS] => Array
    (
        [WEST] => 60.57%
    )

I want to display this table so that the locations are at the top of my table and then the North, South, West and East are the rows like this:

          DETROIT     CHICAGO   NEW YORK   DALLAS
 NORTH     20.00       59.14      N/A       N/A
 SOUTH     30.00       12.94      N/A       N/A
 WEST      25.00       0.00       38.00     60.57
 EAST      N/A         34.60      49.00     N/A

This is what I have so far, but I'm having a hard time formatting it:

   <?
     foreach ($ARR as $LOCATIONS => $RESULTS) {
    ECHO "{$LOCATIONS} <br>";
      foreach ($RESULTS as $PERCENT) {
            echo "{$PERCENT} ";
       echo "<br>";

     }
   }
  ?>
Was it helpful?

Solution

I would use a table to display your table of information. A lot of people refuse to use tables no matter the thing but really a table would handle this perfectly.

<?php
     $stats = array(
        "Detroit"=>array(
        "Stat 1"=> "1000",
        "Stat 2"=> "2000",
        "Stat 3"=> "3000"
        ),
        "Chicago"=>array(
        "Stat 1"=> "4000",
        "Stat 2"=> "5000",
        "Stat 3"=> "6000"
        )
    );
    echo "<table>";
    $heading = "<tr><td>&nbsp;</td>";
    $stats_key = array("Stat 1","Stat 2","Stat 3");
    $cities = array();
    foreach ($stats as $city=>$city_stats){
    $cities[] = $city;
    $heading .= "<td>" . $city . "</td>";
    }
    $heading .= "</tr>";
    foreach ($stats_key as $key){
    $table .= "<tr><td>" . $key . "</td>";
    foreach ($cities as $cit){
     $table .= "<td>" . $stats[$cit][$key] . "</td>";
    }
    $table .= "</tr>";
    }

    echo $heading;
    echo $table;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top