I have dataset like the following, one of my table column let say prices column store prices in json format, example given below.
<?php
$dataSet[] = array(
"product_id" => 1,
"prices" => '{"1":"29990", "2": "10000"}'
);
foreach ($dataSet as $dataRow)
{
$pricesStdClassObject = json_decode($dataRow['prices']);
// Convert stdClass Object into array
$pricesArray = (array) $pricesStdClassObject;
print_r($pricesArray);
}
?>
The output of print_r($pricesArray) is the following
Array ( [1] => 29990 [2] => 10000 )
Then why print_r($pricesArray[1]) give me error
A PHP Error was encountered
Severity: Notice
Message: Undefined offset: 1
But why?
And finally i found the solution:
According to the documentation here and from the forum here I found a ‘assoc’ parameter of json_decoded method that used with this method and by default its value is FLASE, json_decoded return stdClass objects if you want the returned objects converted into associative arrays then you have to make the ‘assoc’ parameter value to TRUE like the following.
$pricesStdClassObject = json_decode($dataRow['prices'], TRUE);
So the above example code will become like this
<?php
$dataSet[] = array(
"prices" => '{"1":"29990", "2": "10000"}'
);
foreach ($dataSet as $dataRow)
{
$pricesArray = json_decode($dataRow['prices'], TRUE);
// returned objects will be converted into associative arrays.
print_r($pricesArray);
}
?>
And then you can access the indexed value with no error message :)
print_r($pricesArray[1]); output: 29990
Array type casting with json decoded StdClass Objects is not working properly, you can skip the following piece of code if you are using the ‘assoc’ parameter.
// Convert stdClass Object into array
$pricesArray = (array) $pricesStdClassObject;
Related
i am fetching data from two tables as below :
$form['form']=json_decode($this->db->get_where('forms',array(
'id' => $id
))->result()[0]->form_sections);
This gives me following result on printing :
Array
(
[form] => Array
(
[0] => Personal_Information
[1] => Education_
[2] => Professional_Life
)
)
Now i have details against each of these array indexes that i am trying to assign them as below
foreach ($form['form'] as $value){
$value->details=$this->db->get_where('formdata',array(
'form_section' => $value
))->result();
}
Which gives me following error
Message: Attempt to assign property 'details' of non-object
can someone please help me to sort out the issue , i have to assign the index and loop in it in my view
This should help understand and clear up the message:
// Custom data
$Person_Info = 404; // Could be any non-object
$array = array("form" => array( 0 => $Person_Info) );
foreach( $array['form'] as $value ){
$results = new stdClass();
$results->name = "User A";
$value->details = $results; // $results are you fetch request
}
// Output: Attempt to assign property 'details' of non-object in php<8.0
// Output: Uncaught Error: Attempt to assign property "details" on int php>=8.0
Try to print_r or var_dump your $value and see what you are getting. It's not an object for some of your array item.
Edit: If ever in doubt about the data. Use if (is_obejct($var)) php.net/is_object or similar checks based on what you need.
I am consuming a web service that returns some XML data. The problems start when I convert the xml data to json. Some elements that are supposed to return an array of objects, when they have only one value, they are not converted to an array with a single object inside, they turn into an object. So instead of having:
{
"products":[ { "title":"Title 1", "attributes":[{"color":"blue"}] } ]
}
I get
{
"products":{ "title":"Title 1", "attributes":{"color":"blue"} }
}
and the php array looks like this
[products] => Array ( [title] => Title 1 [attributes] => Array ( [color] => blue ) )
instead of this
[products] => Array ( [0] => Array ( [title] => Title 1
[attributes] => Array ([0] => Array ([color] => blue ) ) )
So what I have done is the below:
$xml = simplexml_load_string($messageData);
$json = json_encode($xml);
$array = json_decode($json, TRUE);
if (isset($array['products']) && !isset($array['products'][0])) {
$array['products'] = array($array['products']);
}
I check if there is an array named products and if it doesn't have an index 0, I nest it inside a new array.
This does the job. Then I do the same for the attributes array like this:
$products = $array['products'];
$array['products'] = [];
foreach ($products as $product) {
if (isset($product['attributes']) && !isset($product['attributes'][0])) {
$product['attributes'] = array($product['attributes']);
}
array_push($array['products'], product);
}
Here, I bind the products array to a variable called products to use it in the loop, then I empty the array and after I create the new attributes array, I populate the products array with the changed products.
My question is:
Is there a better way to deal with this thing? I don't like what I am doing here, but I can't think of anything else...
EDIT
This is my soap request:
$client = new SoapClient($wsdl, $soapOptions);
$soapHeader = WsSecurity::createWsSecuritySoapHeader($username, $password, false, $synced, 60, true, true, false, true);
$client->__setSoapHeaders($soapHeader);
$response = $client->dateRetrieveMovement($dateMovementRequest);
$movements = $response->DateMovementRequestResult->movements;
$movementInfo = $movements->movementInfo;
$messages = $movementInfo->messages->messageExchanged;
$messageData = $messages->IEMessage->xmlData;
$xml = simplexml_load_string($messageData);
$json = json_encode($xml);
$array = json_decode($json, TRUE);
The question is "is there a better way of doing the XML to JSON conversion", and I think the answer is "not without doing some coding".
Standard XML-to-JSON conversion libraries simply don't know enough about the semantics of your data model to produce a decent representation of your data. In theory a tool could try an extract such information from a schema, or elsewhere, but I don't know of any that does.
Writing a custom XSLT transformation to produce exactly the JSON you want is not too difficult, especially with XSLT 3.0, and this may well be less effort than patching up the JSON in the receiving application in the way you describe.
I have a PHP application with a function that was built to expect information from an API call. However, I'm trying to use this function by passing in information that mimics the API data.
I struggle a bit with arrays and this seems to be an object within an array.
I can access the array that the api provides, so when I use the following code ($triggers is the array the api call returns):
print("<pre>".print_r($triggers,true)."</pre>");
I get the following output:
Array
(
[0] => stdClass Object
(
[triggerid] => 18186
[status] => 0
[value] => 0
)
This is the beginning of the function:
function iterate_triggers($triggers){
$trigger_id_values = array();
foreach($triggers as $trigger) {
//Necessary to show human readable status messages.
$check_status = array(0=>"Up", 1=>"Down", 2=>"Degraded", 3=>"Maintenance");
array_push ($trigger_id_values, [$trigger->triggerid, $trigger->value]);
So if I wanted to pass this function a [triggerid] => 18186 and [value] => 1 how would i do that?
Currently I'm trying:
iterate_triggers(array(0 => array("triggerid" => 18186,"status" => 0,"value" => 1,)));
but this gives me a "Trying to get property of non-object" error. Please be kind to me, I've done my best to research and structure this on my own to no avail.
The easiest way is to cast the assoc array just to an object
In your case this would be
iterate_triggers(array(0 => (object)array("triggerid" => 18186,"status" => 0,"value" => 1,)));
You are currently creating and passing an array that contains an array, while your function expects an array of objects.
You should create your object beforehand, then construct your parameter array, and pass it to your function.
$obj = new \stdClass();
$obj->triggerid = 18186;
$obj->status = 0;
$obj->value = 1;
$arr = array($obj);
iterate_triggers($arr);
This comment on php.net, and the rest of that object documentation, may be useful to you.
By far the easiest and correct way to instantiate an empty generic php object that you can then modify for whatever purpose you choose: <?php $genericObject = new stdClass(); ?>
The error message you are seeing with your own code is caused by $trigger->triggerid inside the function, when $trigger is an array instead of an object as the function expects. Object properties are accessed using $someObject->propertyName notation, while array elements are accessed using $someArray['keyName']
I have this data:
Array
(
[id] => 19936953
[name] => Zackaze
[profileIconId] => 585
[summonerLevel] => 30
[revisionDate] => 1394975422000
)
$str = json_decode($data,true);
$row = (object) $str;
echo $row['name'];
I tried this code but it constantly gives this error:
Fatal error: Cannot use object of type stdClass as array
Hopefully you can help me.
While the conversion to an object is unnecessary (as others have mentioned), that is not the cause of your error. You cannot access object properties using $array['key'] notation. You must use $object->property.
Alternatively, you can remove the $row = (object) $str; line, and then you can access $row as an array.
You already have decoded your json as an associative array since you used true as second parameter so you can print it directly with scopes. If you need to decode as an object simply remove the second parameter, I think you will need to access it in another way though.
$str = json_decode($data,true);
echo $str['name'];
The second argument of json_decode will convert the Object into a Associative Array. Just remove the second argument or change it to false and it will return a stdClass instead of a Associative array.
You can see the Documentation.
Try outputting like
$str = json_decode($data,true);
$str = array
(
'id' => 19936953,
'name' => Zackaze,
'profileIconId' => 585,
'summonerLevel' => 30,
'revisionDate' => 1394975422000
);
$row = (object) $str;
echo $row->name;
Or a cleaner way
$str = json_decode($data);
echo $str->name;
I know my JSON is valid, I'm wanting to pull all the KEY's out of the array and put them in an object. However it seems I can either access ONE objects Key or Value, the entire array, or one key value pair. I have not figured out how to parse out all the keys, or all the values in the array.
Here is what I've tried:
print_r($json_obj) yields:
Array ( [0] => Array ( [0] => uploads/featured/doublewm-4097.jpg [1] => featured ) [1] => Array ( [0] => uploads/featured/moon-5469.jpg [1] => featured ) )
print_r($json_obj[0][1]) yields:
featured
print_r($json_obj[1][0]) yields:
uploads/featured/moon-5469.jpg
print_r($json_obj[1][1]) yeilds:
featured
print_r($json_obj[0][0]) yields:
uploads/featured/doublewm-4097.jpg
PHP Code:
<?php
$resultSet = '[["uploads/featured/doublewm-4097.jpg","featured"],
["uploads/featured/moon-5469.jpg","featured"]]';
$json_obj = json_decode($resultSet);
// print_r($json_obj);
print_r($json_obj[0][1]);
?>
The JSON validates per JSONLint
[
[
"uploads/featured/doublewm-4097.jpg",
"featured"
],
[
"uploads/featured/moon-5469.jpg",
"featured"
]
]
I would like to end up with a object with all the keys in the json_obj... ie:
json_obj = array(
'uploads/featured/moon-5469.jpg',
'uploads/featured/doublewm-4097.jpg'
);
If your input is always in the same format, you can handle it like this
$tmp = json_decode($resultSet);
$json_obj = array();
foreach ($tmp as $values) {
array_push($json_obj, $values[0]);
}
This will give you $json_obj in the desired format with a hardcoded $resultSet like the one you provided.
maybe this is what you are looking for:
json encode server-side like:
echo json_encode($html);
json parse clientside like
var str = JSON.parse(data);
alert (JSON.stringify(str))
I managed to fix it like this:
Changing the json object to this format
data = { gallery: gallery_name,
files: [
// imagefile,imagefile,imagefile...
]
};
And the using the following php
$resultSet = json_decode($_GET['submittedResults'], true);
$gallery = $resultSet['gallery'];
$files_to_zip = $resultSet['files'];