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.
Related
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,
...
]
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);
I am querying an API and the response I get is a Multidimensional Object object(stdClass) that also contains arrays. I need to be able to check if the response is an error condition or was successful. If the response is successful I need to return TRUE. If the response was an error, I need to return the error message contained in the response. The response formats for success and error are completely different. The response for an error looks like this:
object(stdClass)#837 (3) {
["errors"]=> array(1) {
[0]=> object(stdClass)#838 (2) {
["code"]=>int(324)
["message"]=>string(80) "Duration too long, maximum:30000, actual:37081 (MediaId: snf:840912013693931526)"
}
}
["httpstatus"]=>int(400)
["rate"]=>NULL
}
The response for success looks like this:
object(stdClass)#837 (27) {
["created_at"]=> string(30) "Sun Mar 12 13:41:43 +0000 2017"
["id"]=> int(840920745073102850)
["id_str"]=> string(18) "940920795073102850"
["text"]=> string(32) "The Details Posted Here"
["truncated"]=> bool(false)
["entities"]=> object(stdClass)#838 (5) {
["hashtags"]=>
........ Way More is in the Response but it does not matter...
I have tried changing the response to an array then using isset to establish if it was an error, and if so then get the values of the error details like so:
$RESPONSEARRAY = (array) $RESPONSE;
(isset($RESPONSEARRAY["errors"])) {
$ERRORMSG_CODE= $RESPONSEARRAY['errors'][0]['code'];
$ERRORMSG_MESSAGE = $RESPONSEARRAY['errors'][0]['message'];
$ITWASANERROR = $ERRORMSG_CODE.": ".$ERRORMSG_MESSAGE;
return $ITWASANERROR;
} else {
return true;
}
But doing the above give me the following error:
Fatal error: Cannot use object of type stdClass as array
Can anyone suggest a way of doing what I am trying to do with the least overhead on the server. Maybe without needing to convert the stdClass object to an array, or if that has to be done, then that's fine, but I just need it to work. Any help someone can offer would be super appreciated.
Below is the correct way to access the object inside the array.
$RESPONSEARRAY = (array) $RESPONSE;
if(isset($RESPONSEARRAY["errors"])) {
$ERRORMSG_CODE= $RESPONSEARRAY['errors'][0]->code;
$ERRORMSG_MESSAGE = $RESPONSEARRAY['errors'][0]->message;
$ITWASANERROR = $ERRORMSG_CODE.": ".$ERRORMSG_MESSAGE;
return $ITWASANERROR;
} else {
return true;
}
$RESPONSEARRAY = (array) $RESPONSE;
You can get result:
["errors"]=>
array(1) {
[0]=>
object(stdClass)#1 (2) {
["code"]=>
int(324)
["message"]=>
string(80) "Duration too long, maximum:30000, actual:37081 (MediaId: snf:8
40912013693931526)"
}
}
["httpstatus"]=>
int(400)
So $ERRORMSG_CODE= $RESPONSEARRAY['errors'][0]['code']; should be $ERRORMSG_CODE= $RESPONSEARRAY['errors'][0]->code.
And so on
I have this json code:
$cars = '{
"CarBenz":
[
{
"Car": "Benz",
"Color": "Black"
}
]
}';
$json = json_decode($cars , true);
how to print Benz in screen?
print $json['Car'];
$json['Car'] nothing show anything.
To see the type of a variable (and how an object or array is built up) you can use var_dump($json).
In this case, that will give:
array(1) {
["CarBenz"]=>
array(1) {
[0]=>
array(2) {
["Car"]=>
string(4) "Benz"
["Color"]=>
string(5) "Black"
}
}
}
So you need to do $json['CarBenz'][0]['Car'].
First you can var_dump your decoded json string and you can see the array with the structure.
I think you forgot to access the CarBenz element first.
echo $json['CarBenz'][0]['Car'];
If you need all elements in CarBenz you have to iterate over them. Something like that:
foreach($json['CarBenz'] as $car) {
echo $car;
}
My controller code is as below,
$errorData = array(1) {
["val_0"]=>
array(2) {
["created_at"]=>
string(0) ""
["user_email"]=>
string(29) "email address cannot be empty"
}
}
there may be val_1, val_2.... etc.
I just want to pass this array $errorData to template and print it in foreach loop.
How can I do that. I am not able to get what variable to be called in template to access those messages.
Thanks
In your controller, pass data array as below:
$data["error"] = $errorData;
$this->load->view("VIEW_FILE",$data);
In view, your $data extracted. so you will get your error array as $error
foreach($error as $e) // val_0, val_1....
{
//$e is now having val_0 at first loop run
echo $e["created_at"];
echo $e["user_email"];
}