Parsing an un-named JSON array in PHP - php

My question: How can I break up and iterate through the JSON array pictured below?
I am making an AJAX web app and I need to serialize an array of objects in Javascript and put them in a url to pass to a php script. This is all going fine and the php script recieves the JSON like so..
$passed = $_GET['result'];
if(isset($passed)){
$passed = str_replace("undefined" , " " , $passed); /*had to add this to remove the undefined value*/
$json = json_decode(stripslashes($passed));
echo"<br/>";
var_dump($json ); //this is working and dumps an array
}
When I call var_dump on the decoded JSON I echo an output like so...
array(1) { [0]=> object(stdClass)#70 (2) { ["itemCount"]=> int(0) ["ItemArray"]=> array(2) { [0]=> object(stdClass)#86 (6) { ["itemPosition"]=> int(0) ["planPosition"]=> int(0) ["Name"]=> string(5) "dsfsd" ["Description"]=> string(3) "sdf" ["Price"]=> string(0) "" ["Unit"]=> string(0) "" } [1]=> object(stdClass)#85 (6) { ["itemPosition"]=> int(1) ["planPosition"]=> int(0) ["Name"]=> string(4) "fdad" ["Description"]=> string(3) "sdf" ["Price"]=> string(0) "" ["Unit"]=> string(0) "" } } } }
The JSON
This is the JSON I am receiving. It seems like some of the pairs don't have names? How can I access elements in this Array?
Thanks alot guys

Some of these elements are coming back as stdClass objects as you can see in the var_dump output. You can get at the attributes with the standard object notation, for example, with your $json variable:
echo $json[0]->itemCount; // 0
echo $json[0]->itemArray[0]->itemPostion; // 0
You can also iterate over stdClass instances just like any PHP object, you'll be looping through the public data members, so again with your $json:
foreach(echo $json[0]->itemArray[0] as $key => $value)
echo 'key: ' . $key . ', value: ' . $value . PHP_EOL;
will loop through that first object, echoing out the member names and values of the object.

You just access them by index:
data[0] // first data item
Note that that's how you would "normally" access an array in the usual sense, so I might be missing something about your question here...

Related

PHP: how can I access JSON object

I'm sending this JSON:
[{"tipo":""},{"activo":""},{"titulo":"Servicoasd B"},{"texto":"asdasdasd"}]
to a php file via post method.
There, i do
$obj = json_decode($_POST['sentJson']);
However, I seem to be unable to access the elements of the JSON.
var_dump(($obj));
Shows the object:
array(4) {
[0]=>
object(stdClass)#2 (1) {
["tipo"]=>
string(0) ""
}
[1]=>
object(stdClass)#3 (1) {
["activo"]=>
string(0) ""
}
[2]=>
object(stdClass)#4 (1) {
["titulo"]=>
string(9) "Servico B"
}
[3]=>
object(stdClass)#5 (1) {
["texto"]=>
string(6) "asdasd"
}
}
But if I try
$obj['texto'];
$obj->{'texto'};
$obj[0]['texto'];
$obj[0];
It shows "undefined index texto" or "trying to get property of non object in" and the last one "Object of class stdClass could not be converted to string in". I'm very new to PHP, but still I can't seem to notice what I'm doing wrong. Any help would be appreciated.
Your JSON is a serialized array of four completely different objects, so when you run json_decode, that's what you get: an array.
If you want to access your objects inside that array, access them like you would any other indexed array:
$list = json_decode(...);
foreach($list as $obj) {
var_dump($obj)
}
Or target them explicitly using plain old numerical access.
$list = json_decode(...);
$last = $list[3];
$text = $last->texto;
But really the question you should be asking is why this is the JSON you get. An array with completely different objects at each position is terrible data, and should be fixed.

Creating JSON that contains both arrays and objects from a mySQL data source

I am trying to create a JSON representation of data stored in mySQL.
I am trying to document a RESTful API.
I am using PHP's json_encode() function.
I have a table that contains data such as
1) name
2) parent
3) data_type (object/array/string/number to match JSON data types)
4) value
I am trying to create a generalized function that will allow me to build these JSON strings by simply adding data to the mySQL database.
I am having problems with working with both objects and arrays though.
For instance the JSON should be:
{
"sessionToken":"","roleName":""
,"data":[
{
"methodTypes":[""] , "objects":[""]
}
]
}
however it is coming out as:
{
"sessionToken":"","roleName":""
,"data":[
{
"methodTypes":[""]
}
,{
"objects":[""]
}
]
}
this is indicating to me for some reason my code is adding an object for both methodType and objects, where as it should just be within the single object.
I am trying to first create an array containing methodTypes and objects.
Then I create an object in the format of $objects->$A, and I make this equal the array created in the first step.
Then I add in to the primary data array for the JSON generation.
I have been searching for examples that show usage examples of JSON when both arrays and objects are required in the same JSON without success.
Any pointers in the correct direction would be greatly appreciated.
UPDATE #1:
var_dump of the array that is being fed to json_encode() is:
array(3) { ["sessionToken"]=> string(0) "" ["roleName"]=> string(0) "" ["data"]=> array(2) { [0]=> array(1) { ["methodTypes"]=> array(1) { [0]=> string(0) "" } } [1]=> array(1) { ["objects"]=> array(1) { [0]=> string(0) "" } } } }
where as if I take a known good JSON and do a json_decode() then the var_dump looks like:
object(stdClass)#3 (3) { ["sessionToken"]=> string(0) "" ["roleName"]=> string(0) "" ["data"]=> array(1) { [0]=> object(stdClass)#4 (2) { ["methodTypes"]=> array(1) { [0]=> string(0) "" } ["objects"]=> array(1) { [0]=> string(0) "" } } } }
or
array(3) { ["sessionToken"]=> string(0) "" ["roleName"]=> string(0) "" ["data"]=> array(1) { [0]=> array(2) { ["methodTypes"]=> array(1) { [0]=> string(0) "" } ["objects"]=> array(1) { [0]=> string(0) "" } } } }
if I set it to TRUE to return array instead of object.
Edited to give the desired output
$data = ['sessionToken' => '',
'roleName' => '',
'data' => [['methodTypes' => [''], 'objects' => ['']]]
];
And it yields. This works because I wrapped the associative array in a non-associative one
{"sessionToken":"","roleName":"","data":[{"methodTypes":[""],"objects":[""]}]}
EDIT
Some more info on json_encode
Javascript arrays contain only numeric keys. Period. If you have what looks like an associative array, it's really a JS object (which can be referenced using brackets, i.e. var['name'] and var.name are equivalent).
Since json_encode can't create an associative array in JSON, it converts associative PHP arrays into objects instead. So you can see in my example above, I got an object back instead of an array, except where I has not specified keys.
echo json_encode(['name' => 'value']);
Yields
{"name":"value"}
While
echo json_encode(['value']);
Yields
["value"]

How to set a variable inside a PHP object

I want to update two variables in my the Woocommerce cart object. I can see the structure of the arrays in the object with:
echo 'Cart Dump: ' . var_dump($woocommerce->session->cart)
This returns:
array(1) { ["01822dd92bc31f60fdb64f0c3c5eb241"]=> array(9) { ["product_id"]=> int(616) ["variation_id"]=> string(0) "" ["variation"]=> string(0) "" ["quantity"]=> int(1) ["addons"]=> array(2) { [0]=> array(3) { ["name"]=> string(5) "Color" ["value"]=> string(13) "Black / Black" ["price"]=> string(0) "" } [1]=> array(3) { ["name"]=> string(8) "Warranty" ["value"]=> string(13) "12 Month Free" ["price"]=> string(0) "" } } ["line_total"]=> float(689) ["line_tax"]=> float(0) ["line_subtotal"]=> float(689) ["line_subtotal_tax"]=> float(0) } } Cart Dump:
I want to be able to set the variables "value" and "price" inside that object.
My next step has been to try to step into the next array and have tried
echo 'Cart Dump: ' . var_dump($woocommerce->session->cart[1])
but I think I am mixing object references with array ones here and I am getting NULL. I can appreciate that I would be better off creating a function for the object but I am not sure how to best approach that if I cannot even access the variable I want to set.
Many thanks in advance.
There are no objects here, it's just that the array key is the string 01822dd92bc31f60fdb64f0c3c5eb241 and not the integer 1.
So to get / set your value, you would use:
$woocommerce->session->cart["01822dd92bc31f60fdb64f0c3c5eb241"]["addons"][0]["value"]
etc.
Depending on your php version you would probably need a temporary variable to get to the first element of your array if you don't know the key:
$temp = reset($woocommerce->session->cart);
$value = $temp["addons"][0]["value"];
You can try this:
//search the key of the array
$cart = $woocommerce->session->cart;
//update values using the key of the array as key
$woocommerce->session->cart[key($cart)]['value'] = 'your value';
$woocommerce->session->cart[key($cart)]['price'] = 'your price';

php accessing attributes in json

I have the following already decoded json stored in $response = $result->response;:
object(stdClass)#6 (5) {
["EmailAddress"]=> string(18) "email#gmail.com"
["Name"]=> string(0) ""
["Date"]=> string(19) "2011-10-09 19:32:00"
["State"]=> string(6) "Active"
["CustomFields"]=> array(1) {
[0]=>object(stdClass)#7 (2) {
["Key"]=>string(2) "id"
["Value"]=>string(6) "Dl9lIz"
}
}
I can already access the main attributes (EmailAddress, Name, etc) with:
$email = $response->{'EmailAddress'};
print $email;
But I need to access the "Value" portion in the CustomFields object. I don't know how to dig that deep. I'm attempting to do this in PHP..
Any suggestions?
It is contained in the first element ([0]) of array CustomFields, so you can access it with an object operator (->) after the array index.
print $response->CustomFields[0]->Value;

PHP array minor problem

I'm really not sure how to explain this. It's so simple I can't fathom why it's not working.
I have a loop. It puts a bunch of strings into an array. If I fill a single variable with any given string, it will output it perfectly.
But filling an array with the strings will make it give me the dreaded:
Array Array Array Array Array Array Array Array
Note: my strings are not all 'Array'.
The way I loop is:
while(...)
{
$arr[] = $resultFromLoop;
}
Here is my var_dump.
array(1) {
["tagName"]=>
string(5) "magic"
}
array(1) {
["tagName"]=>
string(4) "nunu"
}
array(1) {
["tagName"]=>
string(5) "books"
}
array(1) {
["tagName"]=>
string(0) ""
}
array(1) {
["tagName"]=>
string(3) "zzz"
}
array(1) {
["tagName"]=>
string(4) "grey"
}
array(1) {
["tagName"]=>
string(3) "new"
}
array(1) {
["tagName"]=>
string(6) "flight"
}
This is because you're working with array as with a string.
It puts a bunch of strings into an array.
Nope, there are no strings. I already gave you a magic var_dump($resultFromLoop) function, but you're too lazy to use it for debugging your code (because there is SO, where you can ask any question and don't bother yourself with thinking)

Categories