I'm trying to read the returned json below but i keep getting errors.
Cannot use object of type stdClass as array
I'm fetching the json via curl and then json_decode($data);
foreach($array as $a)
{
switch($a)
{
case"BTC":
//do something
case"ETH":
//do something
}
}
Url :
https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,LTC,XMR,XRP,DASH,ZEC&tsyms=USD
Var Dump Results :
object(stdClass)#405 (6) { ["BTC"]=> object(stdClass)#404 (1) { ["USD"]=> float(13571.4) } ["LTC"]=> object(stdClass)#406 (1) { ["USD"]=> float(235.57) } ["XMR"]=> object(stdClass)#407 (1) { ["USD"]=> float(399.11) } ["XRP"]=> object(stdClass)#408 (1) { ["USD"]=> float(1.83) } ["DASH"]=> object(stdClass)#409 (1) { ["USD"]=> float(1000.25) } ["ZEC"]=> object(stdClass)#410 (1) { ["USD"]=> float(658.29) } }
Decode as Associative Array
For decoding JSON as an array, you have to pass assoc parameter to the json_decode function.
When the assoc parameter is TRUE, returned objects will be converted into associative arrays.
Refer PHP Docs for more information regarding the function.
Example Code
json_decode($data, true);
There is a second parameter to json_decode which allows you to parse json data as associative arrays.
try:
json_decode($data, true);
Related
Need to insert the object in the entries array using array_push method of php where the value for test_view_id will be coming from another array. Can anyone please tell the syntax to do so.
$testViewId = array(12,13,14);
sample object
{
"miscResourceProperties":{
"test_view_id":12
}
}
Expected Output
$data = {
"eventStartTime":1656863552,
"entries":[
{
"miscResourceProperties":{
"test_view_id":12
}
},
{
"miscResourceProperties":{
"test_view_id":13
}
},
{
"miscResourceProperties":{
"test_view_id":14
}
}
]
}
So I can't seem to figure this out, so I'm reaching out to see if someone might be able to help me.
Please let me know what the best output is so that I could use GET to retrieve clean data for the endpoint that I've created.
I have the following method:
function instagram_posts(): bool|string
{
if (!function_exists('is_plugin_active')) {
include_once(ABSPATH . 'wp-admin/includes/plugin.php');
}
if (!is_plugin_active('fh-instagram/autoload.php')) {
return false;
}
if (empty($items = Instagram::get_items_for_api(50))) {
return false;
}
var_dump($items);
var_dump(json_encode($items));
return json_encode($items);
}
var_dump($items); gives me the following output:
array(50) {
[0]=>
object(Plugin\Instagram\Item)#976 (7) {
["id":"Plugin\Instagram\Item":private]=>
}
[1]=>
object(Plugin\Instagram\Item)#1030 (7) {
["id":"Plugin\Instagram\Item":private]=>
string(17) "17842233125750202"
}
}
When I run var_dump(json_encode($items)); I get the following output:
string(151) "[{},{}]"
How can I convert my array of objects so that it can transform it to json and then use it within Postman? This is what it currently looks like in Postman:
array(50) {
[0]=>
object(Plugin\Instagram\Item)#973 (7) {
["id":"Plugin\Instagram\Item":private]=>
string(17) "17992874035441353"
}
[1]=>
object(Plugin\Instagram\Item)#1027 (7) {
["id":"Plugin\Instagram\Item":private]=>
string(17) "17842233125750202"
}
}
It should be outputted such as:
[
{"id": etc..}
]
All help will be appreciated!
The instagram_posts method is being use below:
add_action('rest_api_init', function () {
register_rest_route( 'instagram', '/posts/', [
'methods' => 'GET',
'callback' => 'instagram_posts',
]);
});
So I can use Postman to access the endpoint: http://headlesscms.com.local/wp-json/instagram/posts
Since the property you want is private, it won't be included in the results of json_encode(). Only public properties will.
You need to create a multidimensional array with the structure you want and encode that.
// This is the new array we will push the sub arrays into
$results = [];
foreach($items as $item) {
$results[] = ['id' => $item->get_id()];
}
return json_encode($results);
This will give you a json structure that looks like:
[
{
"id": 1
},
{
"id": 2
},
...
]
Alternative format
If you only want a list of id's, you might not need to create a multidimensional array, but rather just return a list of ids.
In that case, do this:
$results = [];
foreach ($items as $item) {
$results[] = $item->get_id();
}
return json_encode($results);
That would give you:
[
1,
2,
...
]
Seems like an easy thing, but I am not getting the expected data. I want to send an array of strings to my backend and then iterate/do stuff with them.
In the frontend I have:
var jsonArray = ["String1", "String2"]
await newFile(JSON.stringify(jsonArray));
In my controller, I have:
$requestData = json_decode($request->getContent(), true);
$this->logger->info("File request data is ", [ $requestData ]);
My logger outputs:
File request data is ["[\"String1\",\"String2\"]"]
Which is not an array, but a string.
If I do it inside of php with
$txt = ["Test", "Test2"];
$json = json_encode($txt, true);
print_r(json_decode($json));
The output would be an array. Where am I going wrong or what am I missing? Having the true option in json_decode should return me my array.
This
["Test", "Test2"]
is an Array, and this
"[\"String1\",\"String2\"]"
is a string. json_decode() need a string as parameter.
$jsonString = "[\"String1\",\"String2\"]";
$array = json_decode($jsonString, true);
var_dump($array);
/*
array(2) {
[0]=>
string(7) "String1"
[1]=>
string(7) "String2"
}
*/
I have a model that sends an error response to the controller in CodeIgniter that then is passed to the view which is just a JSON encoder. Here is the array from the model.
return $posts[] = array('complete'=>0,'error'=>1003, 'message'=>'Username already exists');
The issue I am having is that I need those square brackets after the $posts variable because sometimes I need an array of errors. However when I pass the single array to the view it encodes the JSON without the square brackets but when I have multiple arrays it includes the square brackets, I need the square brackets in the JSON every time. Here is the Controller...
$data['data'] = $this->logins_model->signup($post_data);
$this->load->view('json', $data);
Here is the view...
header('Content-type: application/json');
$response['response'] = $data;
echo json_encode($response);
I need the JSON response to look like this
{
"response": [
{
"complete": 0,
"error": 1003,
"message": "Username already exists"
}
]
}
NOT THIS!
{
"response": {
"complete": 0,
"error": 1003,
"message": "Username already exists"
}
}
Since you want to get array in json you should be having it in php array as well (i.e. data-structures should meet). So $response['response'] = $data; should be $response['response'] = array($data);
In your example var_dump($response); gives:
array(1) {
["response"]=>
array(3) {
["complete"]=>
int(0)
["error"]=>
int(1003)
["message"]=>
string(23) "Username already exists"
}
}
As you see $response['response'] is an object for json.
When you replace $response['response'] = $data; with $response['response'] = array($data); your data-structure, which you want to convert in json will become:
array(1) {
["response"]=>
array(1) {
[0]=>
array(3) {
["complete"]=>
int(0)
["error"]=>
int(1003)
["message"]=>
string(23) "Username already exists"
}
}
}
That will give you desired output because json_encode will expect that there might be another items in $response['response'].
Demo
Edit
Your model should be returning one dimensional array. For example:
return array('complete'=>0,'error'=>1003, 'message'=>'Username already exists');
And you should assign it to another array that is holding all error messages:
$data['data'][] = $this->logins_model->signup($post_data);
$this->load->view('json', $data);
Demo 2
In your view define $post as an array and remove tha square brackets from there. To check your results in view use print_r instead of echo. Which will show exactly how many data is retrieved.
This question already has answers here:
Convert a PHP object to an associative array
(33 answers)
Closed 6 months ago.
I'm using amazon product advertising api. Values are returned as a multidimensional objects.
It looks like this:
object(AmazonProduct_Result)#222 (5) {
["_code":protected]=>
int(200)
["_data":protected]=>
string(16538)
array(2) {
["IsValid"]=>
string(4) "True"
["Items"]=>
array(1) {
[0]=>
object(AmazonProduct_Item)#19 (1) {
["_values":protected]=>
array(11) {
["ASIN"]=>
string(10) "B005HNF01O"
["ParentASIN"]=>
string(10) "B008RKEIZ8"
["DetailPageURL"]=>
string(120) "http://www.amazon.com/Case-Logic-TBC-302-FFP-Compact/dp/B005HNF01O?SubscriptionId=AKIAJNFRQCIJLTY6LDTA&tag=*********-20"
["ItemLinks"]=>
array(7) {
[0]=>
object(AmazonProduct_ItemLink)#18 (1) {
["_values":protected]=>
array(2) {
["Description"]=>
string(17) "Technical Details"
["URL"]=>
string(217) "http://www.amazon.com/Case-Logic-TBC-302-FFP-Compact/dp/tech-data/B005HNF01O%3FSubscriptionId%3DAKIAJNFRQCIJLTY6LDTA%26tag%*******-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB005HNF01O"
}
}
[1]=>
object(AmazonProduct_ItemLink)#17 (1) {
["_values":protected]=>
array(2) {
I mean it also has array inside objects. I would like to convert all of them into a multidimensional array.
I know this is old but you could try the following piece of code:
$array = json_decode(json_encode($object), true);
where $object is the response of the API.
You can use recursive function like below:
function object_to_array($obj, &$arr)
{
if (!is_object($obj) && !is_array($obj))
{
$arr = $obj;
return $arr;
}
foreach ($obj as $key => $value)
{
if (!empty($value))
{
$arr[$key] = array();
objToArray($value, $arr[$key]);
}
else {$arr[$key] = $value;}
}
return $arr;
}
function convertObjectToArray($data) {
if (is_object($data)) {
$data = get_object_vars($data);
}
if (is_array($data)) {
return array_map(__FUNCTION__, $data);
}
return $data;
}
Credit to Kevin Op den Kamp.
I wrote a function that does the job, and also converts all json strings to arrays too. This works pretty fine for me.
function is_json($string) {
// php 5.3 or newer needed;
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
}
function objectToArray($objectOrArray) {
// if is_json -> decode :
if (is_string($objectOrArray) && is_json($objectOrArray)) $objectOrArray = json_decode($objectOrArray);
// if object -> convert to array :
if (is_object($objectOrArray)) $objectOrArray = (array) $objectOrArray;
// if not array -> just return it (probably string or number) :
if (!is_array($objectOrArray)) return $objectOrArray;
// if empty array -> return [] :
if (count($objectOrArray) == 0) return [];
// repeat tasks for each item :
$output = [];
foreach ($objectOrArray as $key => $o_a) {
$output[$key] = objectToArray($o_a);
}
return $output;
}
This is an old question, but I recently ran into this and came up with my own solution.
array_walk_recursive($array, function(&$item){
if(is_object($item)) $item = (array)$item;
});
Now if $array is an object itself you can just cast it to an array before putting it in array_walk_recursive:
$array = (array)$object;
array_walk_recursive($array, function(&$item){
if(is_object($item)) $item = (array)$item;
});
And the mini-example:
array_walk_recursive($array,function(&$item){if(is_object($item))$item=(array)$item;});
In my case I had an array of stdClass objects from a 3rd party source that had a field/property whose value I needed to use as a reference to find its containing stdClass so I could access other data in that element. Basically comparing nested keys in 2 data sets.
I have to do this many times, so I didn't want to foreach over it for each item I need to find. The solution to that issue is usually array_column, but that doesn't work on objects. So I did the above first.
Just in case you came here as I did and didn't find the right answer for your situation, this modified version of one of the previous answers is what ended up working for me:
protected function objToArray($obj)
{
// Not an object or array
if (!is_object($obj) && !is_array($obj)) {
return $obj;
}
// Parse array
foreach ($obj as $key => $value) {
$arr[$key] = $this->objToArray($value);
}
// Return parsed array
return $arr;
}
The original value is a JSON string. The method call looks like this:
$array = $this->objToArray(json_decode($json, true));