Thursday, 30 August 2018

How do you print the keys and values ​​of an array based on the keys and values ​​of another array?

I have an array that looks like this.

[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%
)

With the help of another user, I got the code to print it out like this table.
          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 my code for printing out the following table:
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;

I have another array, with the keys being the people in charge of these locations.
[John Doe] => Array
(
    [0] => DETROIT
    [1] => DALLAS

)

[Sara Smith] => Array
(

    [1] => NEW YORK
)

 [Donald Duck] => Array
(
    [0] => CHICAGO
)

Now, I just want to print out the same table, but the locations that are under the same person get printed out together, like so:
           DETROIT     DALLAS   NEW YORK   CHICAGO
  NORTH     20.00       N/A      N/A       59.14
  SOUTH     30.00       N/A      N/A       12.94
  WEST      25.00       60.57    38.00     0.00
  EAST      N/A         N/A      49.00     34.60

Any help would be appreciated, thanks.
Edit: This is what I've done so far:
echo "<table>";
$heading = "<tr><td>&nbsp;</td>";
$stats_key = array("Stat 1","Stat 2","Stat 3");
$cities = array();

foreach($PERSON as $per){
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;
}
}

But that extra foreach loop got me too many duplicates. Also, no two people can be in charge of one place.

The last foreach in your code
foreach ($cities as $cit){
    foreach($person_name as $charge){
        if($charge = $cit){
            $table .= "<td>" . $stats[$cit][$key] . "</td>";
            break;
        }else{
            $table .= "<td> N/A </td>";
        }
}

0 comments:

Post a Comment