Reputation: 21
Using Javascript i create an associative object called 'basketItems'. (that resembles an associative array) I then add 'item' objects to this which hold certain item specifications as can be seen below:
// create main basketItems Object
var basketItems = new Object();
function createItem() {
var item = new Object();
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 Object
basketItems[itemUnique] = item;
}
I then send basketItems to the server using post and on the server side my PHP code is:
<?php
$basketItems = $_POST['items'];
print $basketItems;
?>
This gives me the complete basketItems object and outputs it like below as an example:
{ 546523 = { seats = \"FOUR\"; shape = \"HATCHBACK\"; price = \"6500\"; engine = \"TWO LITRE\"; color = \"ORANGE\"; number = \"36408974\"; }; }
I need to be able to call specific parts of the basketItems object though and not just the complete contents. I have tried several attempts using the 'foreach' statement below but i always get an invalid foreach argument:
<?php
$basketItems = $_POST['items'];
foreach($basketItems as $key => $item) {
print $item['shape'];
}
?>
How could i achieve the above so that i can pick out say just the 'shape' value for all items in the basketItems Object?
If anyone could help me out on this i would really appreciate it.
Thank you in advance
---------------------Quick Update--------------------
The javascript is all being used in a mobile app being built in Titanium Appcelerator. I am not posting it with JSON, just as a standard object. The post is sent as below:
var xhr = Ti.Network.createHTTPClient();
xhr.open('POST', 'http://www.xxxxxx.com/xxxxxx.php');
xhr.onload = function () {webview.html = this.responseText;};
xhr.send({items:basketItems});
Upvotes: 2
Views: 1046
Reputation: 3220
Is this suppose to be a JSON string? If yes, it's incorrect format.
{ 546523 = { seats = \"FOUR\"; shape = \"HATCHBACK\"; price = \"6500\"; engine = \"TWO LITRE\"; color = \"ORANGE\"; number = \"36408974\"; }; }
The value of $basketItems is a string not an array. Use json_decode http://php.net/manual/en/function.json-decode.php to decode JSON string and then you can loop over an array.
$basketItems = $_POST['items']; foreach($basketItems as $key => $item) { print $item['shape']; }
Upvotes: 1
Reputation: 145482
Well, your example data is all wrong. But if your input was JSON then it'd be something like:
Note that the same traversal would apply for an actual $_POST array. And it should be exactly like your example foreach.
The input you've shown is neither. It looks like some magic_quotes hampered JSON, but I'm not really sure.
Otherwise before you try anything else, use var_dump($_POST);
to see the actual received structure, before you loop over it.
Upvotes: 1