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.
Related
I am executing an API request, which gives a JSON response like this -
This JSON is too complex for me to work with, so I was looking for a way to eliminate useless stuff. The final JSON I would like should look somewhat like this -
Which means, I am eliminating all items except Display in the records list, and adding them all in a separate list, which just contains the display values. Is it possible to modify JSON with PHP?
Your help/advice will be very appreciated!
This is what you need to do - decode your json to an array, loop through it and create a new array from it and then convert the new array back to json!
-- I created a mock json that is close to yours for this example:
<?php
$json = '{"record":[
{
"id": "FirstId1",
"fields": {
"Display": "ADANI NAVINASH"
},
"created_time" : "20939290"
},
{
"id": "2ndId2",
"fields": {
"Display": "AGRWAL DDDDW"
},
"created_time" : "2343223455"
}
],
"offset": "dsfdgfdsg23432fd"
}';
$array = json_decode($json,true);
echo '<pre>';
print_r($array);
$newArray = []; //Set our new array;
foreach($array['record'] as $record){ //We loop to create our new array
$newArray['records'][] = $record['fields']['Display']; //add the Displays each to a different key
}
$newArray['offset'] = $array['offset']; // add the offset (only one and outside of record so out of the loop)
$newJson = json_encode($newArray); //At the end of it all we take our new array and turn it back to json!
print_r("The new Json: " . $newJson); // print our new json
Which will return this:
Array
(
[record] => Array
(
[0] => Array
(
[id] => FirstId1
[fields] => Array
(
[Display] => ADANI NAVINASH
)
[created_time] => 20939290
)
[1] => Array
(
[id] => 2ndId2
[fields] => Array
(
[Display] => AGRWAL DDDDW
)
[created_time] => 2343223455
)
)
[offset] => dsfdgfdsg23432fd
)
The new Json: {"records":["ADANI NAVINASH","AGRWAL DDDDW"],"offset":"dsfdgfdsg23432fd"}
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']
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'];
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'];
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