Convert Posted Javascript Array into PHP Array

Hi

I need to be able to convert a javascript associative array into a PHP array but i am struggling to get it to work. The main basketItems array will contain item arrays (with a key of itemUnique) which contain the specific item specifications (color,engine etc…)

My javascript arrays are built as below inside a function that gets called on a button press:


// create main basketItems Array
var basketItems = new Array();

function createArray() {
    var item = new Array();
    item["number"] = number variable;
    item["color"] = color variable;
    item["engine"] = engine variable;
    item["shape"] = shape variable;
    item["seats"] = seats variable;
    item["price"] = price variable;

    var itemUnique = unique variable;

    // Add Item into BasketItems Array
    basketItems[itemUnique] = item;
}

I need to be able to pass the javascript arrays through the POST method so i can then use them on the server. Is this possible?

Many thanks in advance for any help

When you post an array from your JS code the PHP core should automatically understand it, if you use var_dump and exit the script the response should be a dump of the sent array with all it’s keys and values intact.

Hi Chris

Thanks for posting about this. I have posted my javascript array to PHP and i can now print the complete basketItems array.

As an example if i have in PHP:


<?php
$basketItems = $_POST['items'];
print $basketItems;
?>

This will output:


{ 546523 = { seats = \\"FOUR\\"; shape = \\"HATCHBACK\\"; price = \\"6500\\"; engine = \\"TWO LITRE\\"; color = \\"ORANGE\\"; number = \\"36408974\\"; }; }

I need to know how i can target specific item specs for all the basketItems array.

For example output just the shape values in basketItems rather than every single value

I have tried numerous:


foreach($basketItems as $key => $value) {
.......
}

but i always get an invalid argument on the foreach.

What you have posted above is a JSON array which firsts needs to be decoded using PHP’s json_decode() function.

I’ve just tried the following which again gives me foreach invalid argument:


<?php
$basketItems = $_POST['items'];
$array = json_decode($basketItems);

foreach($array as $unique => $item) {
	print $item['shape'];
}
?>

I then tried just printing the json_decoded basketItems and it gives me an empty output.


<?php
$basketItems = $_POST['items'];
$array = json_decode($basketItems);

	print $array;

?>

Should this work or am i doing something wrong?

This:
{ 546523 = { seats = \“FOUR\”; shape = \“HATCHBACK\”; …
Is not json.
json will look something like this: $json = ‘{“a”:1,“b”:2,“c”:3,“d”:4,“e”:5}’;
Note the : and not = for assignments.

How are you posting your information?

And BTW, by default json_decode returns an object and not n array. Consult the manual.