thegrede thegrede - 1 month ago 6
Javascript Question

Leave column empty when string not matching to header PHP

Now I have a problem, I don't really know where to start looking at, I want to make a table which contains prices of cars it cost to rent a day, and the header of the table is the car models and on the left side of the table is the rental companies, and I want to put the prices under the car model which the price belong to, and the prices and cars comes out of an array and the car models can be sometimes 5 models and sometimes more or less, so I can't figure out how to sort it with PHP or with JS,

Here is an example what I want to do,

Economy | Midsize | Fullsize
___________________________________________
Hertz | | 60.10 | 70.00
___________________________________________
Avis | $55.22 | 69.10 | 81.56
___________________________________________
Budget | $50.10 | | 70.00


And sometimes can it be like,

Economy | Midsize | Fullsize
___________________________________________
Hertz | 60.10 | | 70.00
___________________________________________
Avis | $55.22 | | 81.56
___________________________________________
Budget | $50.10 | 69.10 | 70.00


The array is like that,

Array(
[Hertz] => Array(
[Economy] => Array(
[0] =>
)
[Midsize] => Array(
[0] => 60.10
)
[Fullsize] => Array(
[0] => 70.00
)
)
[Avis] => Array(
[Economy] => Array(
[0] => 55.22
)
[Midsize] => Array(
[0] => 69.10
)
[Fullsize] => Array(
[0] => 81.56
)
)
[Budget] => Array(
[Economy] => Array(
[0] => 50.10
)
[Midsize] => Array(
[0] =>
)
[Fullsize] => Array(
[0] => 70.00
)
)
)


As you can see in the example above I want to skip a column when I loop the array, and sometimes can be the cars more then 3,

Again it depends on the output of the array what I'm getting.

So where can I found some PHP or JS scripts to do that?

Answer

You could use foreach, this function is helping me about 20% of the day as web developer. All you need to do is to organize your array, in your case you can work with keys as brands and values for the cols, in php it could look like this:

$aData = new array( 
  ["empty"] => new array( 
    [0] => "Economy",
    [1] => "Midsize",
    [2] => "Fullsize", 
    ),
  ["Hertz"] => new array(
    [0] => "",
    [1] => "60.10",
    [2] => "70", 
   ),
);



If your array have this structure, the table will do the rest for you:

<table>
  <?php

  foreach( $aData as $sRowName => $aCols ) {
  ?>
    <tr>
      <td>
        <?php echo $sRowName; ?>
      </td>
      <?php
    foreach( $aCols as $sColData ) {
      if( $sColData !== "empty" ) {
        echo "<td>$sColData</td>";
      }
    } 
  ?>
    </tr>
  <?php   
  }
  ?>
</table>

You can add as many rows and cols to the array as you want, foreach will loop for each item through it ;)