1

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.

3 Answers 3

2

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>';
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Marco. Your piece of code working almost as i need it! Almost because when i select 3 products i have table with schema like: Product 1, Attr 1, Quantity 1, (empty td) in first row. Price 1, Product 2, Attr 2, Quantity 2 in second row. And Price 2, Product 3, Attr 3, Quantity 3 in third. Lastly fourth row with only one td with Price 3. There has been a shift of values in cells. Any ideas?
Sorry! I have $i = 1; and when i change it to $i = 0; as You make it initially it works perfect! +1 and Top answer Mark!
1

Even tough I like Marco Man answer above, I would suggest to reconstruct array from

    [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

To

[0] => Product 1
    [0] => Attr 1
    [1] => Quantity 1
    [2] => Price 1
[1] => Product 2
    [0] => Attr 2
    [1] => Quantity 2
    [2] => Price 2
[2] => Product 3
    [0] =>  Attr 3
    [1] => Quantity 3
    [2] => Price 3
[3] => Product 4
    [0] =>  Attr 4
    [1] => Quantity 4
    [2] => Price 4
[4] => Product 5
    [0] => Attr 5
    [1] => Quantity 5
    [2] => Price 5

Not only it solves your problem, it also allows You to work with same data for different products easier. In my experiance I always had some calculations to do for Total price and other things later. Also If You do something like this once as some resort() function, You could use it as one liner anywhere else.

UPDATE #1 And by the way this type of resorting can be done by simple for (which is faster than foreach)

I'd go for

function resort($arr, $countOfElementsPerProduct) {
    $ret = array();
    for($i = 0; $i < count($arr); $i++) {
        if($i % $countOfElementsPerProduct == 0) {
            if(count($product)) {
                $ret[] = $product;
            }
            $product = array();
        } else {
            $product[] = $arr[$i];
        }
    }
    return $ret;
}

UPDATE #2 In your case, I'd go for something like this:

    $('.ok').on('click', function(e){
        var selectedProducts = [];
        var productsVars = [];
    });
    $("#table tr.selected").each(function(){
        productsVars.push($('td:nth-child(‌​5)', this).html()); //adding attributes in productVars
        productsVars.push($('td:nth-child(6)', this).html());
        productsVars.push($('td:nth-child(8)', this).html());
        productsVars.push($('td:nth-child(10)', this).html());
        selectedProducts.push(productsVars); //variables for each product, separately  
        productsVars = []; //empty your variables for next product
    });
    var myJsonData=selectedProducts;
    $.ajax({data:{MyData:myJsonData}});

10 Comments

Yes Vladimir. This is valuable advice! You have also absolutely right about my intentions with total price, total quantites but im almost totally newbie... Im getting products from select of the table rows with js script like this $('.ok').on('click', function(e){var selected = [];$("#table tr.selected").each(function(){selected.push($('td:nth-child(5)', this).html());selected.push($('td:nth-child(6)', this).html());selected.push($('td:nth-child(8)', this).html());selected.push($('td:nth-child(10)', this).html());}); var myJsonData=selected;$.ajax({data:{MyData:myJsonData}})
So far it works but the array "scheme" is very weak as You mentioned above. I dont have any knowledge how to reconstruct it properly
Checkout updated version of my answer! This will create two dimensional Json. In theory, it might need few edits for your exact case..
@PipBoy2000 My bad, it should be selectedProducts, because it is main array which contains arrays for each product
What I'm doing here is 1. push into productVars all nth-childs for one tr.selected, 2. push array of these vars into selectedProducts, this step will create new element of selectedProducts as array which we filled with variables on lines above, 3. assign empty array to productVars because otherwise we will add another price/qu/attr to already full array in next tr.selected, 4. repeat
|
0

Foreach will appear like this if you have array of values in a variable in PHP:

<table>
    <thead>
        <th>S.No</th>
        <th>Name</th>
    </thead>
    <tbody>
<?php 
$data = $_POST['MyData'];
$i=1;// Auto Increment
foreach($data as $single_value)
{
?>
<tr>
    <td><?php echo $i; ?></td>
    <td><?php echo $single_value; // This will display the value ?></td>
</tr>

<?php
$i++;
}
?>
</tbody>
</table>

In this within the foreach the <tr> will be repeating till how much values you have in array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.