Saleem Saleem - 1 month ago 13
PHP Question

Display PHP array data into table cell with cell number

I have an array from database

Array
(
[0] => stdClass Object
(
[cell] => 2
[price] => 1543.65
)

[1] => stdClass Object
(
[cell] => 3
[price] => 386.22
)

)


and A table

<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
<td>10</td>
<td>12</td>
<td>12</td>
</tr>
<tr>
<?php
print_r($sales);
if(!empty($sales)) {
foreach($sales as $sale) {

if($sale->cell == 1) {echo "<td>".$sale->price."</td>";} else { echo "<td>0</td>"; }
if($sale->cell == 2) {echo "<td>".$sale->price."</td>";} else { echo "<td>0</td>"; }
...
if($sale->cell == 12) {echo "<td>".$sale->price."</td>";} else { echo "<td>0</td>"; }

}

} else {
for($i=1; $i<=12; $i++) {
echo "<td>0</td>";
}
}
?>
</tr>
</table>


I need to display price in same cell as it is in array. Now my problem is array size is not 12. Please help how can I display this on same cell as in
array['cell']
?

I want to display it as:

<tr>
<td>0</td>
<td>1543.65</td>
<td>386.22</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>


Your help and time is appreciated.

Answer

I'm not sure I understand, completely, but this should do it:

echo '<tr>';
foreach($data as $value) {
    $array[$value->cell] = $value->price;
}
for($i = 0; $i <= 12; $i++) {
    echo '<td>';
    if(isset($array[$i])
        echo $array[$i];
    else echo '0';
    echo '</td>';
}
echo '</tr>';

where $data is the array you got from the database and $array is the same data but converted into an associative array. This also assumes 12 columns, so it would be slightly more complex if the total number of columns needs to be flexible.

edit: actually, I just noticed that your array's index doesn't match the 'cell' value. I fixed my code to reflect this, but if this is what your data looks like you should probably reevaluate your data structure.