PHP JSON encode. Echo value [duplicate] - php

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 10 months ago.
I need to echo the value of "summary"
{
"expand":"names",
"startAt":0,
"maxResults":50,
"total":1,
"issues":[
{
"expand":"example",
"id":"129018",
"self":"https://example.com",
"key":"914",
"fields":{
"summary":"Hello there"
}
}
]
}
The below code does not work:
$array_result = json_decode($run_curl, true);
$title = $array_result['issues']['fields']['summary];
What am I doing wrong here? I am pretty sure it's smth simple and obvious.

issues is an array, pass it an index like this:
$title = $array_result['issues'][0]['fields']['summary'];
Note the [0].

I miss something called true at json_decode($json, true);.
If it is true then use: echo $array_result[issues][0][fields][summary];
Online link, This is the online link where you can check it.
$json = '{
"expand":"names",
"startAt":0,
"maxResults":50,
"total":1,
"issues":[
{
"expand":"example",
"id":"129018",
"self":"https://example.com",
"key":"914",
"fields":{
"summary":"Hello there"
}
}
]
}';
JSON Decode
When you start using json_decode, this function makes some array as object, so to access array you need to use the -> sign.
$array_result = json_decode($json);
echo '<pre>';
print_r($array_result);
echo '</pre>';
echo $array_result->issues[0]->fields->summary;
Output
Decoded array:
stdClass Object
(
[expand] => names
[startAt] => 0
[maxResults] => 50
[total] => 1
[issues] => Array
(
[0] => stdClass Object
(
[expand] => example
[id] => 129018
[self] => https://example.com
[key] => 914
[fields] => stdClass Object
(
[summary] => Hello there
)
)
)
)
Hello there

issues is a list ,so you need to add key=0 to get the first element:
$title = $array_result['issues'][0]['fields']['summary'];

Related

PHP accessing array within json object

I created a JSON object in JQuery that looks like this:
var massUpdateDetails = {
checkone: $('#checkone').val(),
checktwo: $('#checktwo').val(),
details: [{
detailone: $('#detailone').val(),
detailtwo: $('#detailtwo').val()
}],
locs: [{
locone: $('#locone').val(),
loctwo: $('#loctwo').val()
}]
}
When I post the massUpdateDetails object to PHP, I can print out the object like this:
<?php
if(isset($_POST['massUpdateDetails'])){
$value = $_POST['massUpdateDetails'];
}
print_r($value);
?>
When using print_r($value), here is what I am seeing:
Array
(
[checkone] => checkoneInfo
[checktwo] => value1,value2
[details] => Array
(
[0] => Array
(
[detailone] => details of one
[detailtwo] => details of two
)
)
[locs] => Array
(
[0] => Array
(
[locone] => loc one
[loctwo] => loc two
)
)
)
I'm trying to set the various values to PHP variable like this:
$checkone= isset($value['checkone']) ? $value['checkone'] : ''; // <-- no problem getting this set
$detailone = isset($value['details']['detailone']) ? $value['details']['detailone'] : ''; // <-- problem is here
echo $detailone;
As you see in the above, I am having a problem setting the variable for $detailone.
When I echo $detailone, I get no error in the console.
What am I doing wrong and how can I fix it?
$value['details'] is an array, so you have to access each element as an array element, e.g. $value['details'][0]['detailone']

How to access this array containing objects in Laravel

The table filed name is called metadata, and within the metadata contained an array of objects such as
[{"title":"Type","value":"Hard Drive (HDD)"},{"title":"Condition","value":"Used"}]
How do I access it using PHP/Laravel. Any help is appreciated. Thanks
You need to decode it, with json_decode() php function :
$x = '[{"title":"Type","value":"Hard Drive (HDD)"},{"title":"Condition","value":"Used"}]';
$y = json_decode($x, true);
print_r($y);
Output :
Array
(
[0] => Array
(
[title] => Type
[value] => Hard Drive (HDD)
)
[1] => Array
(
[title] => Condition
[value] => Used
)
)
Now you can access the value with foreach loop as :
foreach($y as $key => $val) {
echo "Title : " . $val['title'] . $val['value'] ;
}
Above code tested here
The code you have posted is a JSON string. So you first have to decode it to a PHP array with the function json_decode. After that you can access it easily.
Try this out:
$json = '[{"title":"Type","value":"Hard Drive (HDD)"},{"title":"Condition","value":"Used"}]';
$assoc_array = json_decode($json, true); // second parameter is true to get an associative array
echo $assoc_array[0]['title'];

Could not convert json string to array using PHP

I need one help. I am unable to convert string to json array using PHP. I am explaining my code below.
$education=$_POST['education'];
the above line give this output [{'name':'aaa','id':'12'},{'name':'bbb','id':'20'}]. But its coming as a string .I tried to convert into array like below but it gived output as null
$edu=json_decode($education,true);
print_r($edu);
It gives the empty output. Here I need to convert it to array and populate all data. Please help me.
Hi You need to make your json string like below:
$arr = '[{"name":"aaa","id":"12"},{"name":"bbb","id":"20"}]';
$a = json_decode($arr);
echo "<pre>";
print_r($a);
die;
it will show your output like below:
Array
(
[0] => stdClass Object
(
[name] => aaa
[id] => 12
)
[1] => stdClass Object
(
[name] => bbb
[id] => 20
)
)
In php, you can use this function to check valid json:
function _isJsonString($string) {
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
}
You can also check online for valid json: http://json.parser.online.fr/
Hope this will help.

PHP how to properly loop through json with multiple levels as object

Here is the Json data stored in variable $json
[Data] => Array
(
[id_number] => Array
(
[value] => 123445567
[link] => 1234556
[class] =>
)
[date] => Array
(
[value] => 04-18-14
[link] => 1234556
[class] =>
)
Currently I access the lower levels like this:
foreach($json['Data'] as $data) {
foreach ($data['id_number'] as $id) {
print $id['value'];
}
}
There is only one result for id_number and only one result for date. Do I really need this second foreach loop? Isn't there a way to access it by just going to the lower level as an object so it would be something like
print $data->id_number->value
Thank you.
Since you have decoded the JSON string as an array you could do
foreach($json['Data'] as $data) {
print $data['id_number']['value'];
}
If you had decoded it into an object (don't set the second parameter to be true) then you could simply do it like you mentioned
foreach($json->Data as $data)
print $data->id_number->value;
Manual
You can retrieve the elements individually (without looping) by:
$id_number = $json['Data']['id_number']['value'];
$date = $json['Data']['date']['value'];
//etc ...
You can use:
$json['Data'][idnr]->value
If you know the id that is ofc, else you will have to loop

Accessing JSON array after json_decode/multidimensional array

I'm pulling in a search from the Twitter api, fetching the data with file_get_contents and then passing to json_decode which give me this array structure.
{"results":[
{
"from_user":"A-user-name",
"from_user_id":457304735,
"text":"Ich R U #BoysNoize #SuperRola",
"entities":{
"urls":[{
"url":"http:\/\/t.co\/WZnUf68j",
"expanded_url":"http:\/\/instagr.am\/p\/Vz4Nnbnjd6\/",
}]
}]
]
This repeats for every tweet pulled, Now I can access the user name and text using a foreach loop and assigning every instance of results to a variable, then pulling data from the variable.
foreach($jsonArr['results'] as $item){
// Takes the Array jsonArr and for every results heading creates an $item
$user = mysql_real_escape_string($item['from_user']);
$text = mysql_real_escape_string($item['text']);
This saves the correct variables OK, But I can't seem to get the the data within the entities array within the results. If I print out the Entities var like the username or text I get
ArrayArrayArrayArrayArrayArrayArrayArrayArrayArray
So It holds the arrays for each results returned but how on earth do I access it, I've been messing around with a few other methods I know for accessing array data but they all seem to fall flat. Any help with how to get at these values, or integrate them with the foreach would be greatly appreciated
Assuming that you've chosen to decode the JSON as a multi-dimensional array, rather than as objects:
foreach ($results as $tweet) {
$user = $tweet["from-user"];
$text = $tweet["text"];
$entities = $tweet["enities"];
$urls = $entities["urls"];
foreach ($urls as $url) {
echo $url["expanded_url"];
}
}
et cetera
Array
(
[results] => Array
(
[0] => stdClass Object
(
[entities] => Array
(
[0] => stdClass Object
(
[urls] => Array
(
[0] => stdClass Object
(
[expanded_url] => http://instagr.am/p/Vz4Nnbnjd6/
[url] => http://t.co/WZnUf68j
)
)
)
)
[from_user] => A-user-name
[from_user_id] => 457304735
[text] => Ich R U #BoysNoize #SuperRola
)
)
)
Accessing url:
$json_array['results'][0]->entities[0]->urls[0]->url;
Helpful code:
<?php
$json ='{ "results" : [ { "entities" :
[ { "urls" : [ { "expanded_url" : "http://instagr.am/p/Vz4Nnbnjd6/",
"url" : "http://t.co/WZnUf68j"
} ] } ],
"from_user" : "A-user-name",
"from_user_id" : 457304735,
"text" : "Ich R U #BoysNoize #SuperRola"
} ] }';
$json_array = (array)(json_decode($json));
echo '<pre>';
//print_r($json_array);
echo $json_array['results'][0]->entities[0]->urls[0]->url;
?>
Just do a print_r($jsonArr); and you will be able to work with your decoded json.

Categories