简体   繁体   中英

Displaying array from javascript in php

I have an array i make in javascript with 2 columns id and quantity

items.push({
            id : id,
            quantity: quantity
        })

I then use stringify to make it into a jsonstring as shown

var jsonString = JSON.stringify(items);
    $.ajax({
            type: "POST",
            url: "order_process.php",
            data: {data : jsonString}, 
            cache: false,

            success: function(){
            
                window.location.href = "order_confirmation.php";
                

            
            }
});

I then post it to php and use json_decode to turn it into a php array. as shown

$_SESSION['cart'] = json_decode( $_POST['data'] );

The problem is when i use the print_r() function in php, this is the output I get

Array ( 
    [0] => stdClass Object ( [id] => 12 [quantity] => 1 ) 
    [1] => stdClass Object ( [id] => 13 [quantity] => 1 ) 
    [2] => stdClass Object ( [id] => 10 [quantity] => 1 ) 
)

The output I want is as shown below, but I don't know how to format this so I get it as shown

ID quantity
12 1
13 2

Any help would be much appreciated

Use true as the second parameter to json_decode() to get an array instead of an object. Then loop to create your table:

$_SESSION['cart'] = json_decode( $_POST['data'], true );
echo '<table><tr><th>ID</th><th>Quantity</th></tr>';
foreach ($_SESSION['cart'] as $item) {
    echo '<tr><td>'.$item['id'].'</td><td>'.$item['quantity'].'</td></tr>';
}
echo '</table>';

What you're doing in JS is not creating the associative array in the same sense as it is in PHP.

You're actually doing exactly what you get when you JSON decode: You push (append to array) an object (curly braces) with two properties.

What you could do to output array in PHP is either:

  • use what you have and use objects for iteration in PHP
  • pass two regular JS arrays - one with IDs and one with quantities

In any way you would need to know how to wrap the data with HTML so you actually can display the table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM