user254153 user254153 - 5 months ago 35
PHP Question

Make product comparison table from the array

I have array like:

Array
(
[0] => Array
(
[product_id] => 19
[attributes] => Array
(
[0] => Array
(
[label] => Hard Disk
[name] => harddisk
[value] => 500 GB
)

[1] => Array
(
[label] => RAM
[name] => ram
[value] => 16 GB
)

[2] => Array
(
[label] => Graphics
[name] => graphics
[value] => 2 GB
)

[3] => Array
(
[label] => Graphics Card
[name] => graphicscard
[value] => 2 GB
)

)

)

[1] => Array
(
[product_id] => 20
[attributes] => Array
(
[0] => Array
(
[label] => Hard Disk
[name] => harddisk
[value] => 1 TB
)

[1] => Array
(
[label] => RAM
[name] => ram
[value] => 8 GB
)

[2] => Array
(
[label] => Graphics
[name] => graphics
[value] => 1 GB
)

[3] => Array
(
[label] => Graphics Card
[name] => graphicscard
[value] => 1 GB
)

)

)

)


I want to extract this array to tabular form as :

Product ID | 19 | 20
Hard Disk | 500 GB | 1 TB
RAM | 16 GB | 8 GB
Graphics | 2 GB | 1 GB
Graphics Card | 2 GB | 1 GB


There may come another product id also as it is dynamic. I am able to get first column but how to get other column. My code is:

<table class="table">

<?php
$count = count($all);
if (!empty($all)) {
foreach ($all as $value) {
?>
<?php foreach ($value['attributes'] as $val) { ?>
<tr>
<td><?php echo $val['label']; ?></td>
</tr>
<?php
} exit();
}
}
?>
</table>

Answer

I'm always completely baffled by the mixing of HTML and PHP. I prefer a clearer look.

I would solve your problem in two steps:

1: Turn your array into an array that can easily be rendered as a table.

2: Render the table from that array.

if (is_array($all)) {

  // step 1: create table
  foreach ($all as $one) {
    $id = $one['product_id'];
    $table['Product Id'][$id] = $id;
    foreach ($one['attributes'] as $attribute) {
      $label = $attribute['label'];
      $value = $attribute['value'];
      $table[$label][$id] = $value;
    }
  }

  // step 2: render the table
  echo '<table class="table">'.PHP_EOL;
  foreach ($table as $label => $row) {
    echo "<tr><td>$label</td>";
    foreach ($table['Product Id'] as $id) {
      echo '<td>'.(isset($row[$id]) ? $row[$id] : '-').'</td>';
    }
    echo '</tr>'.PHP_EOL;
  }
  echo '</table>'.PHP_EOL;

}

This routine can cope with missing attributes.

This code is not perfect, but it gives you a point to start. The challenge is to reduce the complexity even more. I think that's possible.