I've just started out learning PHP/JSON and I've kind of worked out how to output an array from an json file. My aim is to output all the album titles in <li>'s (in this case they are called collectionName in the json file). I think I maybe going about it the wrong way though.
$artistId = '644708';
$otherAlbumsURL = 'http://itunes.apple.com/lookup?id='. $artistId .'&entity=album';
$a = (array)json_decode(file_get_contents($otherAlbumsURL));
var_dump($a);
If you want an array, just use:
$a = json_decode(file_get_contents($otherAlbumsURL), true);
var_dump($a);
Setting the second parameter in json_decode to TRUE will give you an associative array instead of an object.
Judging from the response of the URL, you'll need to loop through the result like this in order to get any available collection names (the first array element doesn't contain a collection name because it is information about the artist. i.e. it isn't an album):
$artistInfo = $a['results'][0]; //Assign artist info to its own variable.
unset($a['results'][0]); //Delete artist info from the array.
//Loop through the results
foreach($a['results'] as $result){
//$result['collectionName'] has the collection name.
echo $result['collectionName'] . '<br>';
}
Related
I have a serialized array that I need to access:-
a:5:{s:5:"width";i:750;s:6:"height";i:330;s:4:"file";s:25:"2017/12/Sophrologie-1.jpg";s:5:"sizes";a:21:{s:20:"listingpro-blog-grid";a:4:{s:4:"file";s:25:"Sophrologie-1-372x240.jpg";s:5:"width";i:372;s:6:"height";i:240;s:9:"mime-type";s:10:"image/jpeg";}s:21:"listingpro-blog-grid2";a:4:{s:4:"file";s:25:"Sophrologie-1-372x330.jpg";s:5:"width";i:372;s:6:"height";i:330;s:9:"mime-type";s:10:"image/jpeg";}s:21:"listingpro-blog-grid3";a:4:{s:4:"file";s:25:"Sophrologie-1-672x330.jpg";s:5:"width";i:672;s:6:"height";i:330;s:9:"mime-type";s:10:"image/jpeg";}s:23:"listingpro-listing-grid";a:4:{s:4:"file";s:25:"Sophrologie-1-272x231.jpg";s:5:"width";i:272;s:6:"height";i:231;s:9:"mime-type";s:10:"image/jpeg";}s:26:"listingpro-listing-gallery";a:4:{s:4:"file";s:25:"Sophrologie-1-580x330.jpg";s:5:"width";i:580;s:6:"height";i:330;s:9:"mime-type";s:10:"image/jpeg";}s:21:"listingpro-list-thumb";a:4:{s:4:"file";s:25:"Sophrologie-1-287x190.jpg";s:5:"width";i:287;s:6:"height";i:190;s:9:"mime-type";s:10:"image/jpeg";}s:23:"listingpro-author-thumb";a:4:{s:4:"file";s:23:"Sophrologie-1-63x63.jpg";s:5:"width";i:63;s:6:"height";i:63;s:9:"mime-type";s:10:"image/jpeg";}s:25:"listingpro-gallery-thumb1";a:4:{s:4:"file";s:25:"Sophrologie-1-458x330.jpg";s:5:"width";i:458;s:6:"height";i:330;s:9:"mime-type";s:10:"image/jpeg";}s:25:"listingpro-gallery-thumb2";a:4:{s:4:"file";s:25:"Sophrologie-1-360x198.jpg";s:5:"width";i:360;s:6:"height";i:198;s:9:"mime-type";s:10:"image/jpeg";}s:25:"listingpro-gallery-thumb3";a:4:{s:4:"file";s:25:"Sophrologie-1-263x198.jpg";s:5:"width";i:263;s:6:"height";i:198;s:9:"mime-type";s:10:"image/jpeg";}s:25:"listingpro-gallery-thumb4";a:4:{s:4:"file";s:25:"Sophrologie-1-653x199.jpg";s:5:"width";i:653;s:6:"height";i:199;s:9:"mime-type";s:10:"image/jpeg";}s:25:"listingpro-detail_gallery";a:4:{s:4:"file";s:25:"Sophrologie-1-383x330.jpg";s:5:"width";i:383;s:6:"height";i:330;s:9:"mime-type";s:10:"image/jpeg";}s:33:"listingpro-checkout-listing-thumb";a:4:{s:4:"file";s:24:"Sophrologie-1-220x80.jpg";s:5:"width";i:220;s:6:"height";i:80;s:9:"mime-type";s:10:"image/jpeg";}s:31:"listingpro-review-gallery-thumb";a:4:{s:4:"file";s:25:"Sophrologie-1-184x135.jpg";s:5:"width";i:184;s:6:"height";i:135;s:9:"mime-type";s:10:"image/jpeg";}s:17:"listingpro-thumb4";a:4:{s:4:"file";s:25:"Sophrologie-1-272x300.jpg";s:5:"width";i:272;s:6:"height";i:300;s:9:"mime-type";s:10:"image/jpeg";}s:26:"listingpro_location270_400";a:4:{s:4:"file";s:25:"Sophrologie-1-270x330.jpg";s:5:"width";i:270;s:6:"height";i:330;s:9:"mime-type";s:10:"image/jpeg";}s:26:"listingpro_location570_455";a:4:{s:4:"file";s:25:"Sophrologie-1-570x330.jpg";s:5:"width";i:570;s:6:"height";i:330;s:9:"mime-type";s:10:"image/jpeg";}s:26:"listingpro_location570_228";a:4:{s:4:"file";s:25:"Sophrologie-1-570x228.jpg";s:5:"width";i:570;s:6:"height";i:228;s:9:"mime-type";s:10:"image/jpeg";}s:26:"listingpro_location270_197";a:4:{s:4:"file";s:25:"Sophrologie-1-270x197.jpg";s:5:"width";i:270;s:6:"height";i:197;s:9:"mime-type";s:10:"image/jpeg";}s:22:"listingpro_cats270_213";a:4:{s:4:"file";s:25:"Sophrologie-1-270x213.jpg";s:5:"width";i:270;s:6:"height";i:213;s:9:"mime-type";s:10:"image/jpeg";}s:22:"Sophrologie-1-1170x400";a:5:{s:4:"file";s:25:"Sophrologie-1-1170x400jpg";s:5:"width";s:4:"1170";s:6:"height";s:3:"400";s:9:"mime-type";s:10:"image/jpeg";s:7:"nova-wp";b:1;}}s:10:"image_meta";a:12:{s:8:"aperture";s:1:"0";s:6:"credit";s:0:"";s:6:"camera";s:0:"";s:7:"caption";s:0:"";s:17:"created_timestamp";s:1:"0";s:9:"copyright";s:19:"Maygutyak - Fotolia";s:12:"focal_length";s:1:"0";s:3:"iso";s:1:"0";s:13:"shutter_speed";s:1:"0";s:5:"title";s:0:"";s:11:"orientation";s:1:"0";s:8:"keywords";a:0:{}}}
I want to retrieve the Sophrologie-1-1170x400jpg filename from it (at the bottom of the array).
I can't figure out how to retrieve this filename into this array. The clue is that there is a nova-wp value in that row.
This array comes fromwp-postmeta table in an wordpress installation.
If you could bring me to the direction, I'll be very thankful.
The data you show has been produced through serialization. Use the unserialize function in order to bring it back to its original state:
$data = unserialize($text);
Then, traverse the deserialized data it in order to retrieve the value you are looking for:
echo $data["sizes"]["Sophrologie-1-1170x400"]["file"];
// Output: Sophrologie-1-1170x400jpg
A working demo can be found here.
If you need to scan your data in order to find the correct value, you can use the following code:
$data = unserialize($text);
if (array_key_exists("Sophrologie-1-1170x400", $data["sizes"])) {
echo $data["sizes"]["Sophrologie-1-1170x400"]["file"];
} else {
echo "File not found!";
}
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);
Confusing title, the basics are that I'm saving a fully sorted and ordered multidimensional array from a script and into MySQL. I then, on another page, pull it from the database and unserialize it, and then proceed to print it out with this,
$s = "SELECT * FROM gator_historical_data WHERE channelid = '{$chanid}'";
$r = $link->query($s);
$comboarray = array();
while ($row = mysqli_fetch_assoc($r)) {
$comboarray[] = unserialize($row['dataarray']);
}
foreach ($comboarray as $item) {
$desc = $item['content']['description'];
$title = $item['content']['title'];
$datetime = $item['datetime'];
// ... ^^^ problems getting array data
}
The problem is that it doesn't take the full array from MySQL, only the first entry and thus only prints the first 'array'. So where the returned value from dataarray looks like this (var_dump): http://pastebin.com/raw.php?i=Z0jy55sM the data stored into the unserialized $comboarray only looks like this (var_dump): http://pastebin.com/raw.php?i=Ycwwa924
TL;DR: Pulling a serialized multidimensional array from a database, unserializing and it loses all arrays after the first one.
Any ideas what to do?
The string you've got is a serialized string plus something more at the end that is also a serialized string again and again:
a:3:{s:6:"source";s:25:"World news | The Guardian";s:8:"datetime ...
... story01.htm";}}a:3:{s:6:"source";s:16:"BBC News - World";
^^^
This format is not supported by PHP unserialize, it will only unserialize the first chunk and drop everything at the end.
Instead create one array, serialize it and store that result into the database.
Alternatively you can try to recover for the moment by un-chunking the string, however in case the paste was done right, there are more issues. But on the other hand the paste obvious isn't the done fully correct.
I"m creating a PHP script that handles JSON input (via a $_POST variable). It"s extracts data from the JSON and uploads it to an SQL database. I want the JSON in a particular format:
$object = json_decode('{
"key_a":[{"value_a":10,"value_b":7},{"value_a":10,"value_b":7},{"value_a":10,"value_b":7}],
"key_b":[{"value_a":10,"value_b":7}],
"key_c":[{"value_a":10,"value_b":7},{"value_a":10,"value_b":7}]
}',true);
Basically, an object with keys in, each of which should hold an array (no matter what size it is). I use json_decode(json,true) to convert it to an associative array (as opposed to object). I"ve had to add lots of checks in for each of the keys, checking if they"re objects or arrays (as the ASP.net page that the extract comes from converts arrays with single objects in, to objects - removing the array that holds them). The checks then convert them back to arrays, if there"s an object where I"d like an array holding an object:
if(is_object($object["key_b"]))
{
$a = array();
$a[] = $object["key"];
$object["key"] = $a;
}
I then iterate through the array, adding the values to rows in an SQL database. This all works fine, but when converting back to JSON with json_encode, any keys that hold arrays with only one object in, remove the array, and leave just the object under that key:
echo(json_encode($object));
// RETURNED JSON
'{
"key_a":[{"value_a":10,"value_b":7},{"value_a":10,"value_b":7},{"value_a":10,"value_b":7}],
"key_b":{"value_a":10,"value_b":7},
"key_c":[{"value_a":10,"value_b":7},{"value_a":10,"value_b":7}]
}'
You see, key_b no longer holds an array, but an object! This is really annoying, as I plan to create a JavaScript script that iterates through the arrays, adding one DOM element (div) for each of the objects.
Why does this happen? Is there any way to keep them as arrays, even if there"s only one object in the array?
I"ve tried:
if(is_object($object["key_b"]))
{
$a = array();
$a[] = array_values($object["key"]);
$object["key"] = $a;
}
and
if(is_object($object["key_b"]))
{
$a = array();
$a[0] = array_values($object["key"]);
$object["key"] = $a;
}
But it seems like nothing prevents json_encode from affecting the JSON in this way.
It"s not hard to get around this - but it means adding one check per key (checking whether it"s an array or value), which is particularly time consuming as the data extract that comes through is really big.
Any advice would be greatly appreciated.
EDIT: changed ' to " in JSON - though, this is only an example I just wrote to show the structure.
EDIT: I'm using references to cut my coding time down, if this changes anything?:
$t =& $object["key_b"];
if(is_object($t))
{
$a = array();
$a[] = $t;
$t = $a;
}
It appears using is_object() on a key of an associative array will not return true. I just knocked up this example, to prove this:
$json = json_decode('{"job_details":{"a":[{"x":5},{"y":23},{"z":18}],"b":{"x":19},"c":[{"x":64},{"y":132}]}}',true);
echo(json_encode($json)."<br><br>");
$t =& $json["job_details"]["b"];
if(is_object($t))
{
$a = array();
$a[] = $t;
$t = $a;
echo("IS OBJECT<br><br>");
}
echo(json_encode($json));
I will find another means of checking what value is held within an associative arrays key.
I was actually trying to find whether the value in the key is an associative array or not (not an object) - I just didn't realise they were different in PHP.
I must just use this custom function:
function is_assoc($array)
{
return (bool)count(array_filter(array_keys($array), 'is_string'));
}
From: How to check if PHP array is associative or sequential?
Which returns true if the value is an associative array.
I have a JSONArray generated in java and I post it to one of my PHP files where it's saved to a file. From there it gets read and I need to generate a chart based on this data. All I need is to convert my raw JSON which has values I don't need, into a simply php array.
[{"id":1,"timestamp":"1363135091","reward":1200,"player":"Orangeguy24","address":"108.28.239.167","service":"MC-Index"},{"id":2,"timestamp":"1363135091","reward":1200,"player":"Orangeguy24","address":"108.28.239.167","service":"MC-Index"}]
Is an example of 2 elements inside my JSON array. What I need todo is filter those values into arrays accordingly.
For example get how many votes a 'player' has, I need to add up how ever many elements are in the JSONArray, because 1 element is 1 vote (the id is primary auto-increment in my mysql DB, not located on my webserver)
I'd like the array to be to [player, votes] so when I echo the array it will be easily parsed by the google chart tools I'm using. I've spent the last 5 hours working on this and I've been stuck, thanks for any help!
To decode the JSON into a php array, you can do:
$json_array = json_decode($raw_json);
Then, to get the number of votes for each player out of the array:
$player_votes = array_reduce($json_array,
function($v, $item) {
if(!array_key_exists($item->player, $v))
$v[$item->player] = 1;
else
$v[$item->player] = 1 + $v[$item->player];
return $v;
}, array());
If I understand your question correctly, this will work.
EDIT: Updated the second code snippet
Try this :
$str = '[{"id":1,"timestamp":"1363135091","reward":1200,"player":"Orangeguy24","address":"108.28.239.167","service":"MC-Index"},{"id":2,"timestamp":"1363135091","reward":1200,"player":"Orangeguy24","address":"108.28.239.167","service":"MC-Index"}]';
$res = array();
foreach(json_decode($str,true) as $val){
if(array_key_exists($val['player'],$res)){
$res[$val['player']] = $res[$val['player']]+1;
}
else{
$res[$val['player']] = 1;
}
}
echo "<pre>";
print_r($res);
Output :
Array
(
[Orangeguy24] => 2
)