PipBoy2000 PipBoy2000 - 3 months ago 8
PHP Question

How to make a foreach loop with array data given

I have

array data
like this taken from .js to JSON, and next to PHP

Ok: Array
(
[MyData] => Array
(
[0] => Product 1
[1] => Attr 1
[2] => Quantity 1
[3] => Price 1
[4] => Product 2
[5] => Attr 2
[6] => Quantity 2
[7] => Price 2
[8] => Product 3
[9] => Attr 3
[10] => Quantity 3
[11] => Price 3
[12] => Product 4
[13] => Attr 4
[14] => Quantity 4
[15] => Price 4
[16] => Product 5
[17] => Attr 5
[18] => Quantity 5
[19] => Price 5
)
)


In PHP I have something like this

$data = $_POST['MyData'];


And MyData data is get by $data[0]....[39] variable in email template etc.
Like here:

$message = '<!DOCTYPE HTML>'.
(...)
'<table cellpadding="15">'.
'<tr style="background-color: #ffffff;">'.
'<td><p>'.$data[0].'</p></td>'.
'<td><p>'.$data[1].'</p></td>'.
'<td><p>'.$data[2].'</p></td>'.
'<td><p>'.$data[3].'</p></td>'.
'</tr>'.
'<tr style="background-color: #ffffff;">'.
'<td><p>'.$data[4].'</p></td>'.
'<td><p>'.$data[5].'</p></td>'.
'<td><p>'.$data[6].'</p></td>'.
'<td><p>'.$data[7].'</p></td>'.
'</tr>'.
'</table>'.
(...)
;


How to make a loop (
foreach
?) handle this table tr row generation?
The problem exist because array sometimes has only 1 product (
Array 0 to 3
), and sometimes may have 40 products... You rather know where is the problem - i don't want to make, a large
HTML/PHP
email template with hundreds of array value id's ;)
I'm learning
js, JSON, ajax and PHP
so please be patient on my newbie question.

Answer

You could try something like:

$i = 0;
$output = '<table cellpadding="15">'.
              '<tr style="background-color: #ffffff;">'.;

foreach($data as $row)
{
    if($i % 4 === 0)
    {
        $output .= '</tr>'.
                   '<tr style="background-color: #ffffff;">';
    }

    $output .= '<td><p>'.$row.'</p></td>';
    $i++;
}

$output .= '</tr>'.
       '</table>';