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;
Related
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.
I have written an xml-parser to read an XML-file. The XML-file is not mine so I can't change the structure. Things work great till I got to this special point. I want to read a value but I don't have a key to access this value.
I marked the values (in red) in the screenshot below which I want to access.
When I dump the parent element (the PRAT->VALUE) I get this in return:
object(SimpleXMLElement)#31 (3) { ["#attributes"]=> array(5) { ["nr"]=> string(1) "1" ["unit"]=> string(3) "bar" ["unit_id"]=> string(4) "3103" ["vo"]=> string(0) "" ["vo_id"]=> string(0) "" } [0]=> string(2) "20" [1]=> string(1) "2" }
As seen, at the end of the dump the values that I want to access are presented. I tried to access it like an array but that doesn't work. The values are not part of the attributes.
use (String) keyword in front of it.
eg.
echo (String) PRAT->VALUE;
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';
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...
I think I am either just stupid or something but I still can't get my head around them.
I am trying to access "patient_age" from this variable $result.
Here is the var dump.
array(1) {
["intervention"]=>
array(1) {
[0]=>
object(stdClass)#23 (21) {
["intervention_id"]=>
string(1) "1"
["patient_id"]=>
string(1) "1"
["name_id"]=>
string(1) "1"
["department_id"]=>
string(1) "1"
["dosage_id"]=>
NULL
["edocument"]=>
string(10) "Bruce1.jpg"
["user_id"]=>
string(1) "0"
["duration"]=>
string(8) "02:26:00"
["submitted"]=>
string(19) "2011-07-31 19:56:29"
["intervention_comment"]=>
NULL
["patient_age"]=>
string(2) "34"
["patient_height"]=>
string(4) "1.34"
["patient_weight"]=>
string(2) "45"
["patient_gender"]=>
string(4) "Male"
["department_name"]=>
string(10) "Cardiology"
["intervention_name_id"]=>
string(1) "1"
["intervention_name"]=>
string(5) "IVH 2"
["intervention_description"]=>
string(0) ""
["dosage_emitted"]=>
NULL
["dosage_absorbed"]=>
NULL
["dosage_period"]=>
NULL
}
}
}
I have tried :
$result[0]->patient_age;
$result[1]->patient_age;
$result['intervention']->patient_age;
$result['intervention'][0]->patient_age;
Hopefully someone could give me the answer but also explain how they came to this answer as all the other Stackoverflow questions they just give the solution but not the method.
Anyone got any tips how to navigate nested variables.
Thanks
$object=$result['intervention'][0];
print $object->patient_age;
Check if any other variables are accessable
It should be your last example. It's not that hard, really. $result is an array which contains a single element, with the key "intervention". You can access an array's elements by using [ and ]. So, with $result['intervention'], you get an array that also contains a single element: the element at key 0, which is an instance of stdClass. You can reach that by using $result['intervention'][0]. If you want to get the patient_age from that stdClass, you can access the instance variables with the ->. So, this should work:
echo $result['intervention'][0]->patient_age;
The following would result in $patient being the stdClass instance, which you can then retrieve patient_age from:
$patient = $result['intervention'][0];
echo $patient->patient_age;
$result[0]->patient_age;
will work *as long as patient_age is a public variable*. If it's private or protected you'll need to use a method within the object to access it.
You never said what happened with the stuff you tried. Null values? Error/warning messages?
Proof:
<?php
class iv {
var $patient_age;
function __construct($val)
{
$this->patient_age=$val;
}
}
$t=new iv(40);
$result=array(0=>$t);
var_dump($result) . "\n\n";
print "val = " . $result[0]->patient_age . "\n\n";
[user#example ~]$ php -q t.php
array(1) {
[0]=>
object(iv)#1 (1) {
["patient_age"]=>
int(40)
}
}
val = 40
[user#example ~]$