This question already has answers here:
Pretty-Printing JSON with PHP
(27 answers)
Closed 6 months ago.
Having an array printed with print_r method:
Array
(
[0] => Array
(
[id] => 44
[item_level] => 0
[position] => 10
[parent_position] =>
[title] => PHP Tutorial
[qty] => 0
[comment] =>
[status] =>
[unit] =>
)
[1] => Array
(
[id] => 46
[item_level] => 1
[position] => 20
[parent_position] =>
[title] => Algorithms
[qty] => 1
[comment] =>
[status] =>
[unit] =>
)
[2] => Array
(
[id] => 48
[item_level] => 2
[position] => 30
[parent_position] => 20
[title] => PHP and MySQL Databases
[qty] => 1
[comment] =>
[status] =>
[unit] =>
)
)
I'm trying to encode it as JSON using either:
json_encode($array, JSON_NUMERIC_CHECK);
json_encode($array);
The output in both cases is the following though:
[{"id":"44","item_level":0,"position":10,"parent_position":"","product_id":"","title":"PHP
Tutorial","qty":0,"comment":"","status":"","unit":""},{"id":"46","item_level":1,"position":20,"parent_position":"","title":"Algorithms","qty":1,"comment":"","status":"","unit":""},{"id":"48","item_level":2,"position":30,"parent_position":20,"title":"PHP
and MySQL
Databases","qty":1,"comment":"","status":"","unit":""}]
Yes, there are the newline characters put between some, but not all, space-separated words. In Postman, the response arrives broken into multiple lines, the same happens when my frontend gets this kind of response, causing it to report JSON parsing error.
How to transform the array to JSON format properly?
PHP version here is 7.0.33.
Tried to look for any non-printable characters that might have been added on the way, as it was suggested in the comments, but wasn't able to locate any.
Anyway, pretty printing solved the issue in a satisfying way:
json_encode($array, JSON_PRETTY_PRINT);
The only thing to be considered, is casting numbers to proper types on arrival to frontend, since JSON_PRETTY_PRINT prints out all of them as strings (i.e. {"quantity": "1"}).
Related
This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 8 days ago.
I have an array that I have run json_decode on it...
How can I echo the category_name Hoops from $myarray?
The following is the output of
echo"<pre>;
print_r($myarray);
echo"</pre>;
Array
(
[Althetic] => Array
(
[0] => Array
(
[category_id] => 1
[category_name] => Balls
[parent_id] => 0
)
[1] => Array
(
[category_id] => 2
[category_name] => Hoops
[parent_id] => 0
)
[2] => Array
(
[category_id] => 3
[category_name] => Strings
[parent_id] => 0
)
)
[rawRequest] => Hello world
[hasError] => 1
[errorMessage] => OK
)
I tried
echo $myarray[Althetic][1]->[category_name];
Without any results :(
T
This is a multidimensional array, -> is used to access elements of object.
$myarray['Althetic'][1]['category_name'];
This question already has answers here:
How to get single value from this multi-dimensional PHP array [duplicate]
(6 answers)
Closed 5 years ago.
I have an array:
print_r($response);
will show:
Response: Array
(
[errors] => false
[return] => Array
(
[price_recurring] => 0
[country_code] => NL
[invoicemethod] => instant
[product_id] => 0
[affiliate] =>
[number_of_periods] => 1
[description] => Betaling voor eventid 274
[period_duration] => 1 month
[date] => 29/11/2017 19:42
[order_quantity] => 1
[vat] => 21
[amount_total] => 4599
[total_paused_days] => 0
[custom] => WEB1511980957x194237
[emailaddress] => ik#ik.nl
[amount_affiliate_initial] => 0
[total] => 45,99
[current_status] => completed
[amount_affiliate_recurring] => 0
[amount_total_affiliate] => 0
[id] => 1790226
[price_initial] => 4599
[current_number_of_periods] => 1
[firstname] =>
)
)
How can i extract the value 'custom'?
I've tried:
$response = array_shift($response);
echo $response['custom'];
but it will show nothing. What am i doing wrong here? I know i am close.
$response is an array with two keys errors and return. $response['return'] in turn, is an array with several keys, including custom. Therefore, to access custom, you need to reference $response['return']['custom']
you have an array inside an array
$response["return"]["custom"]
also try to var_dump (or print_r depends on what you prefer) instead of echoing when you try to navigate
var_dump( $response["custom"]);
would tell you a lot more than echoing null, which prints nothing
This question already has answers here:
How can I access an array/object?
(6 answers)
Closed 6 years ago.
I have a JSON data which I am trying to parse, but my code is not working. I get the error
unexpected '->' (T_OBJECT_OPERATOR).
The array structure looks like this:
Array
(
[mautic.lead_post_save_update] => Array
(
[0] => Array
(
[lead] => Array
(
[isPublished] => 1
[dateAdded] => 2016-09-15T08:08:20+00:00
[createdBy] => 1
[createdByUser] => Deepak Tiwari
[dateModified] => 2016-12-20T14:20:36+00:00
[modifiedBy] => 1
[modifiedByUser] => Deepak Tiwari
[id] => 149269
[points] => 100
[color] =>
[fields] => Array
(
[core] => Array
(
[compulsation] => Array
(
[id] => 39
[label] => Job
[alias] => compulsation
[type] => text
[group] => core
[field_order] => 2
[object] => lead
[value] => 0
and so on. I need to access the value of "job compultion". The code I am using is:
$json = file_get_contents('php://input');
$data=json_decode($json,TRUE);
$job=data->mautic.lead_post_save_update->0->lead->fields->core->compulsation->value;
I am not getting any value in $job.
You're using object property syntax (->) to access array elements, which won't work. Your code should use array syntax ([...]), like this:
$json = file_get_contents('php://input');
$data=json_decode($json,TRUE);
$job=data['mautic.lead_post_save_update'][0]['lead']['fields']['core']['compulsation']['value'];
That's what the error message is trying to tell you. A decent IDE, like PHPStorm (no affiliation), would help you catch errors like this.
Your json_decode() is not creating a object. Its an array and you can get your variables by using [] instead of the ->
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I fetch an array from API using
<?php
$json = json_decode(file_get_contents("API_URL"), TRUE);
echo '<pre>';
print_r($json);
?>
I got that result like that
Array
(
[deals] => Array
(
[0] => Array
(
[activeDa
te] => 1430332361000
[bogo] =>
[categories] => Array
(
[0] => Array
(
[id] => 29057
[name] => Bath & Body
)
[1] => Array
(
[id] => 20733
[name] => Cosmetics
)
[2] => Array
(
[id] => 29190
[name] => Skin Care
)
[3] => Array
(
[id] => 20856
[name] => Fragrances
)
[4] => Array
(
[id] => 29059
[name] => Beauty & Personal Care
)
)
[clearance] =>
[couponCode] => HAPPYMOM
[dealImageUrl] => http://cdn.savings.com/logo/1737578.png
[dealUrl] => http://www.savings.com/m/p/19561077/8306099/c?afsrc=1&up=2015-05-01-05-15
[description] => Go through this link to get Assorted Spring Getaway tote for only $20 on orders $40 or more, save 80%. Restrictions may apply. Limited time offer only or when supplies run out.
[discount] => 1
[exclusive] =>
[freeShipping] =>
[homePageStaffPick] =>
[id] => 3862713
[lastUpdated] => 1430332361000
[merchantDisplayUrl] => http://www.bathandbodyworks.com
[merchantId] => 236514
[merchantImageUrl] => http://cdn.savings.com/logo/1737578.png
[merchantName] => Bath and Body Works
[merchantPageStaffPick] =>
[merchantScore] => 17
[merchantUrl] => http://www.savings.com/m/p/19561077/1742990/c?afsrc=1
[minimumSpend] => 0.00
[mobileMonetized] =>
[monetized] => 1
[printable] =>
[promotion] => 80% Off
[rebate] =>
[scope] => SITE_WIDE
[score] => 579
[siteUrls] => Array
(
[0] => http://www.bathandbodyworks.com
)
[startDate] => 1430290800000
[tip] =>
[title] => Get 80% off Assorted Spring Getaway Tote on Orders Over $40 - Only $20
[validated] =>
[voteDown] => 0
[voteUp] => 0
)
My question is how i get the value of [deals][categories][0][name] ?
I want to store value of categories name.
You have your answer in your question itelf. just a little modifiction needed. Please try this:-
echo $yourarrayname['deals'][0]['categories'][0]['name'];
Note:-since category is on the Zero th index of deals. So put zero index before category index.
You already have your answer. The only thing you need to do is make them literal strings and take the first element in the deals array. So:
echo $json['deals'][0]['categories'][0]['name']
This question already has an answer here:
how to decode this JSON string?
(1 answer)
Closed 8 years ago.
Respected All,
I have a string which I got from an api. Now I want to extract useful data from this string. This output is a result of Json query.
the string is
{"PR":{"Url":"http://www.ididthisfilm.com/lex_tmp2/custom-form/","Domain":"http://www.ididthisfilm.com","Title":"Lexicon Of Sustainability – Custom Form","Description":"Welcome to THE LIST EDIT FORM","Pictures":[{"Url":"http://www.ididthisfilm.com/lex_tmp2/wp-content/uploads/2014/05/Lexicon_logo_new_BETA.png","Alt":"Lexicon Of Sustainability","Title":"","SourceType":1,"Width":0,"Height":0,"ParsedAspectRatio":0}],"Videos":[],"AuthorName":null,"ExtraInfo":null},"EM":null}`
How can I get title and description and url in different variables so that I can use them in php.
use built-in function json_decode and you will get the JSON object.
$str=<<<CODE
{"PR":{"Url":"http://www.ididthisfilm.com/lex_tmp2/custom-form/","Domain":"http://www.ididthisfilm.com","Title":"Lexicon Of Sustainability - Custom Form","Description":"Welcome to THE LIST EDIT FORM","Pictures":[{"Url":"http://www.ididthisfilm.com/lex_tmp2/wp-content/uploads/2014/05/Lexicon_logo_new_BETA.png","Alt":"Lexicon Of Sustainability","Title":"","SourceType":1,"Width":0,"Height":0,"ParsedAspectRatio":0}],"Videos":[],"AuthorName":null,"ExtraInfo":null},"EM":null}
CODE;
print_r( json_decode($str) );
which outputs
stdClass Object
(
[PR] => stdClass Object
(
[Url] => http://www.ididthisfilm.com/lex_tmp2/custom-form/
[Domain] => http://www.ididthisfilm.com
[Title] => Lexicon Of Sustainability – Custom Form
[Description] => Welcome to THE LIST EDIT FORM
[Pictures] => Array
(
[0] => stdClass Object
(
[Url] => http://www.ididthisfilm.com/lex_tmp2/wp-content/uploads/2014/05/Lexicon_logo_new_BETA.png
[Alt] => Lexicon Of Sustainability
[Title] =>
[SourceType] => 1
[Width] => 0
[Height] => 0
[ParsedAspectRatio] => 0
)
)
[Videos] => Array
(
)
[AuthorName] =>
[ExtraInfo] =>
)
[EM] =>
)
if any error occurs, try this: json_last_error()