We are importing our JSON from an API. The JSON is pulling through fine but unordered
We want to order the JSON file by the name field, We have used uasort but it does not seem to take effect?
$url="https://dev-api.ourwebsite.com";
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// DUMPING THE JSON
$json=json_decode($result, true);
uasort($json, 'name');
foreach($json as $value) {
$course_name=$value["name"];
}
usort() (or uasort() if you need to keep the keys of the array) is what you need:
<?php
// mocking some data
$json = [
["name" => "paul"],
["name" => "jeff"],
["name" => "anna"]
];
uasort($json,
// this callable needs to return 1 or -1, depending on how you want it to sort
function($a, $b) {
if($a['name']>$b['name']) {
return 1;
} else {
return -1;
}
});
var_dump($json);
foreach($json as $value) {
$course_name=$value["name"];
echo $course_name."<br>";
}
// output:
array(3) {
[2]=>
array(1) {
["name"]=>
string(4) "anna"
}
[1]=>
array(1) {
["name"]=>
string(4) "jeff"
}
[0]=>
array(1) {
["name"]=>
string(4) "paul"
}
}
anna
jeff
paul
Related
I receive data asynchronously (curl_multi_exec) from JSON.
As a result, how to divide the received data into 2 variables ($response_url and $response_url2)?
I need two variables to continue working with each JSON separately.
$urls = [
"https://rssbot.ru/1.json",
"https://rssbot.ru/2.json"
];
$mh = curl_multi_init();
$allResponse = [];
foreach($urls as $k => $url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_multi_add_handle($mh, $ch);
$allResponse[$k] = $ch;
}
$running = null;
do {
curl_multi_exec($mh, $running);
} while($running > 0);
foreach($allResponse as $id => $ch) {
$response = curl_multi_getcontent($ch);
curl_multi_remove_handle($mh, $ch);
$response = (json_decode($response));
var_dump($response);
}
curl_multi_close($mh);
echo $response_url;
echo $response_url2;
var_dump:
array(2) {
[0]=>
object(stdClass)#1 (3) {
["symbol"]=>
string(7) "XRPBUSD"
["price"]=>
string(6) "0.3400"
["time"]=>
int(1671427537235)
}
[1]=>
object(stdClass)#2 (3) {
["symbol"]=>
string(7) "MKRUSDT"
["price"]=>
string(6) "542.60"
["time"]=>
int(1671427559567)
}
}
array(3) {
[0]=>
object(stdClass)#2 (2) {
["symbol"]=>
string(6) "ETHBTC"
["price"]=>
string(10) "0.07081400"
}
[1]=>
object(stdClass)#1 (2) {
["symbol"]=>
string(6) "LTCBTC"
["price"]=>
string(10) "0.00377700"
}
[2]=>
object(stdClass)#3 (2) {
["symbol"]=>
string(6) "BNBBTC"
["price"]=>
string(10) "0.01482300"
}
}
Thanks!
$results = [];
$prev_running = $running = null;
do {
curl_multi_exec($mh, $running);
if ($running != $prev_running) {
$info = curl_multi_info_read($mh);
if (is_array($info) && ($ch = $info['handle'])) {
$content = curl_multi_getcontent($ch);
$url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
$results[$url] = ['content' => $content, 'status' => $info['result'], 'status_text' => curl_error($ch)];
}
$prev_running = $running;
}
} while ($running > 0);
Use list function.
An example :
$urls = [
"https://rssbot.ru/1.json",
"https://rssbot.ru/2.json"
];
list($a, $b) = $urls;
// $a : string(24) "https://rssbot.ru/1.json"
// $b : string(24) "https://rssbot.ru/2.json"
I want to retrieve all names from my database and send it to all the registered phones by gcm.
I get an error at my android side
Error
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.util.ArrayList.get(int)' on a null object reference
at reminder.com.org.remind.GCMPushReceiverService.onMessageReceived(GCMPushReceiverService.java:27)
this is the result of var_dump($message)
array(1) { ["message"]=> array(3) { [0]=> string(5) "name1" [1]=> string(5) "name2" [2]=> string(5) "name3" } }
Please help. Thanks.
PHP Server Code
<?php
include('db_connect.php');
DEFINE('GOOGLE_API_KEY','my_google_api_key');
$db = new DB_CONNECT();
$conn = $db->connect();
$gcmRegids = array();
$names = array();
$sql = "SELECT * FROM Test";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
array_push($gcmRegids, $row['reg_id']);
array_push($names, $row['name']);
}
if(isset($gcmRegids)) {
$e = "ads";
$message = array('message' => $names);
var_dump($message);
$pushStatus = sendPushNotification($gcmRegids,$message);
}
function sendPushNotification($reg_ids, $message) {
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $reg_ids,
'data' => $message,
);
$headers = array (
'Authorization: key='. GOOGLE_API_KEY,
'Content-type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($fields));
$result = curl_exec($ch);
if($result === false) {
die('Curl failed:'. curl_error($ch));
}
curl_close($ch);
//echo $result;
return $result;
}
?>
array(1) { ["message"]=> array(3) { [0]=> string(5) "name1" [1]=> string(5) "name2" [2]=> string(5) "name3" } }
Android code
public class GCMPushReceiverService extends GcmListenerService {
public final static String s = "msg";
ArrayList<String> arr = new ArrayList<String>();
#Override
public void onMessageReceived(String from, Bundle data) {
if(data != null) {
arr = data.getStringArrayList("message");
Log.d("Names:",arr.get(0));
}
}
.....
}
You can't get simply an Php Array into Android/java array .. you have to convert it.. try to change your php script as..
$message = array('message' => json_encode($names));
it will convert your php array($names) into json.
than get the JSON in android as..
String message = data.getString("message");
Log.e(TAG, "Message: " + message);
now convert it into JsonArray as..
JsonArray array = new JsonArray(message);
now loop on it and get the content of Php array names.
I think here you are doing wrong.
change your code as below and try again
if (isset($gcmRegids) && count($gcmRegids) > 0) {
$e = "ads";
$message = array('message' => $names);
var_dump($message);
foreach ($gcmRegids as $gcmid) {
$pushStatus = sendPushNotification($gcmid, $message);
}
}
Here's the relevant part of my PHP:
$response2 = curl_exec( $ch2 );
$stuff2 = json_decode($response2, true);
$user_id = $stuff2['identities[0].user_id'];
The $response looks good, as does $stuff2. What I'm trying to get is the value for user_id and store as a variable I can use in PHP ($user_id). If I var_dump $stuff2, I get something like this:
array(2) {
["nickname"]=>
string(3) "jmr"
["identities"]=>
array(1) {
[0]=>
array(2) {
["user_id"]=>
string(24) "5458fec4aa0395931002fe71"
["connection"]=>
string(32) "Username-Password-Authentication"
}
}
}
If I do this:
$response2 = curl_exec( $ch2 );
$stuff2 = json_decode($response2, true);
$user_id = $stuff2['nickname'];
then I get "jmr" no problem, but I can't figure out how to get that "user_id" buried in that second array within the array.
Do a print_r($stuff2); and you will see the array is just an ordinary multi-dimensional array. I'm not sure why you have that convoluted key, but you access it just like an ordinary multi-dimensional array:
$user_id = $stuff2['identities'][0]['user_id'];
I have a JSON array directly from an API and one piece of it looks like this:
{
"type": "champion",
"version": "4.4.3",
"data": {
"Aatrox": {
"id": "Aatrox",
"key": "266",
"name": "Aatrox",
"title": "the Darkin Blade",
"stats": {
"armor": 14.0,
"armorperlevel": 3.8,
"attackdamage": 55.0,
"attackdamageperlevel": 3.2,
"attackrange": 150.0,
"attackspeedoffset": -0.04,
"attackspeedperlevel": 3.0,
"crit": 0.0,
"critperlevel": 0.0,
"hp": 395.0,
"hpperlevel": 85.0,
"hpregen": 5.75,
"hpregenperlevel": 0.5,
"movespeed": 345.0,
"mp": 30.0,
"mpperlevel": 45.0,
"mpregen": 0.0,
"mpregenperlevel": 0.0,
"spellblock": 30.0,
"spellblockperlevel": 1.25
}
},
and then it simply repeats this for every other champion. I used cURL to turn that into a PHP array, which looks like this:
$url="api_url_blah";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
$array = json_decode($result, true);
From there, I made a foreach loop to list all the champions and their "armor" stat, however the armor won't display but the champion name does:
$i = 1;
foreach($array['data'] as $champs)
{
echo $champs['id']. "<br>";
foreach($champs['stats'] as $stats) {
echo $stats['armor'];
}
$i++;
}
As I said, the champion name comes up but the second foreach loop is returning nothing. Also, I was wondering what would be the most convenient way to make it so (after this works) I can call just one champion's stats based on a PHP variable and not all 118 of them at one time.
This is the var_dump() of the array:
array(3) { ["type"]=> string(8) "champion" ["version"]=> string(5) "4.4.3" ["data"]=> array(118) { ["Aatrox"]=> array(5) { ["id"]=> string(6) "Aatrox" ["key"]=> string(3) "266" ["name"]=> string(6) "Aatrox" ["title"]=> string(16) "the Darkin Blade" ["stats"]=> array(20) { ["armor"]=> float(14) ["armorperlevel"]=> float(3.8) ["attackdamage"]=> float(55) ["attackdamageperlevel"]=> float(3.2) ["attackrange"]=> float(150) ["attackspeedoffset"]=> float(-0.04) ["attackspeedperlevel"]=> float(3) ["crit"]=> float(0) ["critperlevel"]=> float(0) ["hp"]=> float(395) ["hpperlevel"]=> float(85) ["hpregen"]=> float(5.75) ["hpregenperlevel"]=> float(0.5) ["movespeed"]=> float(345) ["mp"]=> float(30) ["mpperlevel"]=> float(45) ["mpregen"]=> float(0) ["mpregenperlevel"]=> float(0) ["spellblock"]=> float(30) ["spellblockperlevel"]=> float(1.25) } }
You don’t need a second foreach loop. The following code should work:
$i = 1;
foreach($array['data'] as $champs){
echo $champs['id'] . "<br/>" . $champs['stats']['armor'] . "<br/>";
$i++;
}
I am a code like below
<?php
$movie_name="Dabangg 2";
$movie_name = urlencode($movie_name);
$url="http://api.themoviedb.org/3/search/movie?api_key=accd3ddbbae37c0315fb5c8e19b815a5&query=$movie_name";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Accept: application/json"));
$response = curl_exec($ch);
curl_close($ch);
$obj = json_decode($response);
foreach ($obj->results as $results){
echo $results->id;
echo $results->"http://d3gtl9l2a4fn1j.cloudfront.net/t/p/w92'.poster_path.'";
}
?>
and var_dump is
object(stdClass)#1 (4) {
["page"]=>
int(1)
["results"]=>
array(1) {
[0]=>
object(stdClass)#2 (10) {
["adult"]=>
bool(false)
["backdrop_path"]=>
string(32) "/rWGMdyTydjXXh9YphuU5gQ7wJ8X.jpg"
["id"]=>
int(147405)
["original_title"]=>
string(9) "Dabangg 2"
["release_date"]=>
string(10) "2012-12-21"
["poster_path"]=>
string(32) "/3tqT7N94fY73Ft6BVepnEqgwWyr.jpg"
["popularity"]=>
float(0.46)
["title"]=>
string(9) "Dabangg 2"
["vote_average"]=>
float(5.8)
["vote_count"]=>
int(2)
}
}
["total_pages"]=>
int(1)
["total_results"]=>
int(1)
}
my code is working fine. I just want to retrieve the poster_path with the base URL http://d3gtl9l2a4fn1j.cloudfront.net/t/p/w92 . HOw can I do this? The above
echo $results->"http://d3gtl9l2a4fn1j.cloudfront.net/t/p/w92'.poster_path.'";
is just my attempt to echo the full URL.
The output URL echo should be
http://d3gtl9l2a4fn1j.cloudfront.net/t/p/w92/3tqT7N94fY73Ft6BVepnEqgwWyr.jpg
Thanks
Unless im missing something...
echo 'http://d3gtl9l2a4fn1j.cloudfront.net/t/p/w92' . $results->poster_path;
This might help you:
<?php
$url_ahead = 'http://d3gtl9l2a4fn1j.cloudfront.net/t/p/w92';
$poster_path = $results[0]['poster_path']; //or something like this
//$poster_path = "/3tqT7N94fY73Ft6BVepnEqgwWyr.jpg"; //for static
// echo $url_ahead.''.$poster_path;
echo $url_ahead.$poster_path;
?>
$baseUrl = "http://d3gtl9l2a4fn1j.cloudfront.net/t/p/w92";
foreach ($obj->results as $results){
echo $results[0]->id; //this also should be changed from $results->id
$posterUrl = $results[0]['poster_path'];
echo $baseUrl.$posterUrl; //Can store like $poster_path = $baseUrl.$posterUrl;
}
Why need to use $results[0]->id and $results[0]['poster_path']? Because $results is also a Two/Multidimensional array.