user3312802 user3312802 - 1 month ago 12
PHP Question

Multi-dimensional Array Calculation

This is the

Array
that I want to display in the
HTML table
.

$itemss =array(
array( "name"=>"Blue Pen", "Description"=>"Atlas", "UnitPrice"=>13.50, " AvailableStock "=>200),
array( "name"=>"80 P-Book", "Description"=>"Atlas", "UnitPrice"=>65," AvailableStock "=>100),
array( "name"=>"A4 Paper 500", "Description"=>"Atlas", "UnitPrice"=>500," AvailableStock "=>20),
array( "name"=>"Red Pen", "Description"=>"Atlas", "UnitPrice"=>13.50," AvailableStock "=>256),
array( "name"=>"Back Pen", "Description"=>"Atlas", "UnitPrice"=>13.50," AvailableStock "=>156) );


The output should be like this in a table.

Item Name |Description|Unit Price|Available Stock|Stock Value

Blue Pen Atlas 13.50 200 xxxx


Total Stock Value |xxxxxx


And this what I have done up to now:

<?php
$itemss =array(
array( "name"=>"Blue Pen", "Description"=>"Atlas","UnitPrice"=>13.50,"AvailableStock"=>200),
array( "name"=>"80 P-Book", "Description"=>"Atlas", "UnitPrice"=>65," AvailableStock"=>100),
array( "name"=>"A4 Paper 500","Description"=>"Atlas","UnitPrice"=>500,"AvailableStock"=>20),
array( "name"=>"Red Pen", "Description"=>"Atlas", "UnitPrice"=>13.50,"AvailableStock"=>256),
array( "name"=>"Back Pen", "Description"=>"Atlas", "UnitPrice"=>13.50,"AvailableStock"=>156) );


?>
<table border="1">
<tr>
<th>Item Name</th>
<th>Description</th>
<th>Unit Price</th>
<th>Available Stock</th>
<th>Stock Value</th>


</tr>
<?php
foreach($itemss as $Rockband)
{
echo '<tr>';
foreach(array_values($Rockband) as $key => $item)
{
echo "<td>$item</td>";

}
echo '</tr>';
}
?>
</table>

Answer
<table border="1">
<tr>
<th>Item Name</th>
<th>Description</th>
<th>Unit Price</th>
<th>Available Stock</th>
<th>Stock Value</th>


</tr>
<?php
$TotalStockValue = 0;

foreach($itemss as $Rockband)
{
    echo '<tr>';
    foreach( $Rockband as $key => $value )
    {
        echo "<td>$value</td>";
    }
    $StockValue = ( $Rockband["UnitPrice"] * $Rockband["AvailableStock"] );
    echo '<td>' . $StockValue . '</td>';
    echo '</tr>';

    $TotalStockValue += $StockValue;
}
echo '<tr><td colspan="4">Total Stock Value</td><td>' . $TotalStockValue . '</td></tr>';
?>
</table>