I am trying to select a variable from an array (at least I think it's stored as an array):
$data = json_encode($response);
file_put_contents('file.txt', $data);
gives
"status":200,"response":{
"api_id":"0f42d6be-8ed2-11e3-822e-22135",
"bill_duration":36,
"call_duration":36,
"total_rate":"0.00300"}
}
How can I select the call_duration value (in php)? I've tried $response['call_duration'], which I thought should work but returns nothing?
$response['call_duration'] was very nearly correct, but I think you need:
$response['response']['call_duration']
Looking at your output after converting to json, I think the original array, $response, looks like this (in PHP array format)
$response = array(
'status'=>200,
'response'=>array(
'api_id'=>'0f....etc',
'bill_duration'=>36,
... etc
)
);
So, you need to go an extra level deep into the array to get call_duration.
Related
I have a script that loops through and retrieves some specified values and adds them to a php array. I then have it return the value to this script:
//Returns the php array to loop through
$test_list= $db->DatabaseRequest($testing);
//Loops through the $test_list array and retrieves a row for each value
foreach ($test_list as $id => $test) {
$getList = $db->getTest($test['id']);
$id_export[] = $getList ;
}
print(json_encode($id_export));
This returns a JSON value of:
[[{"id":1,"amount":2,"type":"0"}], [{"id":2,"amount":25,"type":"0"}]]
This is causing problems when I try to parse the data onto my android App. The result needs to be something like this:
[{"id":1,"amount":2,"type":"0"}, {"id":2,"amount":25,"type":"0"}]
I realize that the loop is adding the array into another array. My question is how can I loop through a php array and put or keep all of those values into an array and output them in the JSON format above?
of course I think $getList contains an array you database's columns,
use
$id_export[] = $getList[0]
Maybe can do some checks to verify if your $getList array is effectively 1 size
$db->getTest() seems to be returning an array of a single object, maybe more, which you are then adding to a new array. Try one of the following:
If there will only ever be one row, just get the 0 index (the simplest):
$id_export[] = $db->getTest($test['id'])[0];
Or get the current array item:
$getList = $db->getTest($test['id']);
$id_export[] = current($getList); //optionally reset()
If there may be more than one row, merge them (probably a better and safer idea regardless):
$getList = $db->getTest($test['id']);
$id_export = array_merge((array)$id_export, $getList);
I am trying to unset a value from test_bots.json and save it back, but somehow the data format is being changed in the process.
test_bots.json contains this JSON array:
["John","Vladimir","Toni","Joshua","Jessica"]
My code looks like this:
$good = 'Toni';
$good_arr = file_get_contents('test_bots.json');
$good_arr = json_decode($good_arr);
if(in_array($good, $good_arr)){
$key = array_search($good, $good_arr);
unset($good_arr[$key]);
$good_arr2 = json_encode($good_arr);
file_put_contents('test_bots.json',$good_arr2);
}
The output that's saved is:
{"0":"John","1":"Vladimir","3":"Joshua","4":"Jessica"}
but I want the output to look like:
["John","Vladimir","Joshua","Jessica"]
I tried to unserialize the array before saving it, but it's not working.
Why is this happening?
In order for json_encode to convert a PHP array with numeric keys to a JSON array rather than a JSON object, the keys must be sequential. (See example #4 in the PHP manual for json_encode.)
You can accomplish this in your code by using array_values, which will reindex the array after you have removed one of the items.
$good_arr2 = json_encode(array_values($good_arr));
I have a result, $result, returned from an SQL query which contains the following data: [{"TOTAL":"12345"}]
I want to put that result into a JSON API with a route of, say, /api/total/ and have it return: {total:12345}. I'll be setting the first half of that manually, e.g. 'total' => whatever in the Slim framework.
$app->render(200, array(
'total' => $result["TOTAL"]
)
);
How do I reference 12345 from the returned array? Doing $result["TOTAL"] doesn't work.
The result looks like [{"TOTAL":"12345"}]?
So you have to json_decode it first.
$decodedResult = json_decode($result, true);
echo $decodedResult[0]['TOTAL'];
Use this code , you will get the value.
$result = '[{"TOTAL":"12345"}]';
$res = json_decode($result);
echo $res[0]->TOTAL;
Please try this
$res = json_decode($result);
even though there is only one object in the array, it is still an array so you need to reference the object's index.
$result[0]["TOTAL"]
I am trying to get json data from the Statcounter API.
I have the following:
$query = makeQuery("2292634", "demo_user", "statcounter", "visitor", "");
echo $query . "<br>";
$response = file_get_contents($query, true);
$data = json_decode($response, true);
echo $data['sc_data']['log_visits'];
I know the query is correct, and I know the $response is filled with unformatted json. The trouble is accessing the array and pulling the values out.
Here are the first couple lines of the unformatted json it is giving me.
This link will only work for 15 minutes, I can generate a new one if you would like to see the raw json.
http://api.statcounter.com/stats/?vn=3&s=visitor&pi=2292634&t=1398791335&u=demo_user&sha1=c6cdfd6c84227801c6ca758c17252712e3f76514
{"#attributes":{"status":"ok"},"sc_data":[{"log_visits":"1","entries_in_visit":"2","entry_t":"2014-04-29 17:57:33","entry_url":"http:\/\/www.guitar-online.com\/en\/","entry_title":"Learn how to play the guitar: tutorials, guitar
Obviously I am not accessing the array in the correct way...but I haven't found the syntax to make it work YET!
Thank you for your help.
Looking at your data, sc_data is an array containing nested JSON objects so you should be able to iterate over that array to read the data like you want:
echo $data['sc_data'][0]['log_visits'];
The code above will access the first element of the array sc_data and print the value of log_visits
When you have {"field":['a','b','c']} in JSON, you would access 'a' as field[0].
The elements of the array can be any valid value, i.e.
string
number
object
array
true
false
null
In your case it is objects and you access that object the same way you would access any other array element - by the index number (JSON doesn't have associative array of type "key" => "value")
I'm trying to get the "screenshotUrls" string from this piece of json:
$request_url = 'http://itunes.apple.com/search?term=ibooks&country=us&entity=software&limit=1';
$json = file_get_contents($request_url);
$decode = json_decode($json, true);
echo $decode['results'][0]['screenshotUrls'];
But I get only text "Array"
What have I done wrong?
Try
var_dump($decode['results'][0]['screenshotUrls']);
IF you get 'Array' output by PHP that means that you're trying to echo an actual array (or the string 'Array'...). That means you need to get a specific index value.
Since $decode['results']['0']['screenshotUrls'] is an array, if you want just a string (say, delimited by commas), you could use
echo implode(",", $decode['results']['0']['screenshotUrls']);
This will iterate over the array, and return a comma-separated string of all the URLs.
Do a var_dump($decode['results']['0']['screenshotUrls']). You'll find that the ['screenshotUrls'] is actually an Array, containing one or more URLs (hence the plural 'urls' in its name).
There's nothing wrong with your code so far, but $decode['results'][0]['screenshotUrls'] is an array of all the URLs to screenshots. To go through each one individualy, you need to do:
forearch ($decode['results'][0]['screenshotUrls'] as $url) {
// Do stuff here
}