PHP function help - php

This is the function:
function NewsDat($url="http://www.url.com/dat/news.dat", $max=5){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$curlresult = curl_exec($ch);
$posts = explode("\n", $curlresult); //chop it up by carriage return
unset($curlresult);
$num=0;
$result=array();
foreach($posts as $post){
$result[] = explode("::", $post);
$num++;
if($num>$max-1){
break;
}
}
return $result;
}
var_dump(NewsDat());
Which returns:
array(5) { [0]=> array(14) { [0]=> string(10) "1183443434" [1]=> string(1) "R" [2]=> string(46) "Here is some text"...
I need to echo: 1183443434 and Here is some text...
Can anyone help?

Basic array handling?
$result = NewsDat();
echo $result[0][0]; //holds "1183443434"
echo $result[0][2]; //holds "Here is some text"
But I don't know if the values are always at this positions when you run your function.

Well as NewsDat return an array of arrays, if you need this two fields on each lines, this should do the trick:
$news = NewsDat();
foreach($news as $single_new)
{
echo $single_new[0] . " - " . $single_new[2] . "\n";
}
If you only need these two fields, just:
$news = NewsDat();
$field1 = $news[0][0];
$field2 = $news[0][2];
echo $field1 . " - " . $field2 . "\n";

Related

how to format a json file?

I am new to JSON and I am wondering how i could format my JSON file so I will be able to render it in a barchart.
I've got the following PHP code:
<?php
$search_value=$_POST["search"];
$mysqli = new mysqli('localhost','root','password','mydb');
$myArray = array();
if ($result = $mysqli->query("SELECT * FROM transcriptome WHERE genename LIKE '%$search_value%'")) {
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$myArray = $row;
}
file_put_contents('jsonoutput.json', json_encode($myArray));
echo json_encode($myArray);
}
$result->close();
$mysqli->close();
?>
My actual output:
(given a gene (xkr4) as input)
{"genename":"xkr4","TA11MEAN":"974.25","TA11STD":"99.0085223605","TA21MEAN":"710.75","TA21STD":"115.79831605","TA22MEAN":"736.5","TA22STD":"115.79831605","TA23MEAN":"903.75","TA23STD":"107.283211641","TB11MEAN":"799.25","TB11STD":"97.2660655111","TB21MEAN":"658","TB21STD":"91.7959694104","TB22MEAN":"592.75","TB22STD":"70.9379129944","TB23MEAN":"864","TB23STD":"92.7280971443"}
How I'd like to get my output:
{"genename":"xkr4",{"TA11MEAN":"974.25"},{"TA11STD":"99.0085223605"},{"TA21MEAN":"710.75"},{"TA21STD":"115.79831605"},{"TA22MEAN":"736.5"},{"TA22STD":"115.79831605"},{"TA23MEAN":"903.75"},{"TA23STD":"107.283211641"},{"TB11MEAN":"799.25"},{"TB11STD":"97.2660655111"},{"TB21MEAN":"658"},{"TB21STD":"91.7959694104"},{"TB22MEAN":"592.75"},{"TB22STD":"70.9379129944"},{"TB23MEAN":"864"},{"TB23STD":"92.7280971443"}}
If someone could give me direction on this (or solve it) That would be great!
Thanks in advance :)
I would suggest you to first check how are you getting back your data in array.
$myArray[] should have the data populated as shown below. Then use JSON_PRETTY_PRINT.
/*USED TO SHOW FULL ARRAY SIZE*/
ini_set('xdebug.var_display_max_depth', -1);
ini_set('xdebug.var_display_max_children', -1);
ini_set('xdebug.var_display_max_data', -1);
$myArray=array("genename"=>array(array("xkr4"=>array(
array("TA11MEAN"=>"974.25","TA11STD"=>"99.0085223605"),
array("TA21MEAN"=>"710.75","TA21STD"=>"115.79831605"),
array("TA22MEAN"=>"736.5","TA22STD"=>"115.79831605"),
array("TA23MEAN"=>"903.75","TA23STD"=>"107.283211641"),
array("TB11MEAN"=>"799.25","TB11STD"=>"97.2660655111"),
array("TB21MEAN"=>"658","TB21STD"=>"91.7959694104"),
array("TB22MEAN"=>"592.75","TB22STD"=>"70.9379129944"),
array("TB23MEAN"=>"864","TB23STD"=>"92.7280971443"),
))));
$jsonData=json_encode($myArray,JSON_PRETTY_PRINT);
var_dump($jsonData);
$json_from_database='[{"genename":"xkr4","TA11MEAN":"974.25","TA11STD":"99.0085223605","TA21MEAN":"710.75","TA21STD":"115.79831605","TA22MEAN":"736.5","TA22STD":"115.79831605","TA23MEAN":"903.75","TA23STD":"107.283211641","TB11MEAN":"799.25","TB11STD":"97.2660655111","TB21MEAN":"658","TB21STD":"91.7959694104","TB22MEAN":"592.75","TB22STD":"70.9379129944","TB23MEAN":"864","TB23STD":"92.7280971443"}]';
//print decode array from databse
$decoded=json_decode($json_from_database);
var_dump($decoded);
foreach ($decoded[0] as $key => $value) {
echo "\n ";
print $key;
print " " .$decoded[0]->$key;
}
array(1) {
[0]=>
object(stdClass)#1 (17) {
["genename"]=>
string(4) "xkr4"
["TA11MEAN"]=>
string(6) "974.25"
["TA11STD"]=>
string(13) "99.0085223605"
["TA21MEAN"]=>
string(6) "710.75"
["TA21STD"]=>
string(12) "115.79831605"
["TA22MEAN"]=>
string(5) "736.5"
["TA22STD"]=>
string(12) "115.79831605"
["TA23MEAN"]=>
string(6) "903.75"
["TA23STD"]=>
string(13) "107.283211641"
["TB11MEAN"]=>
string(6) "799.25"
["TB11STD"]=>
string(13) "97.2660655111"
["TB21MEAN"]=>
string(3) "658"
["TB21STD"]=>
string(13) "91.7959694104"
["TB22MEAN"]=>
string(6) "592.75"
["TB22STD"]=>
string(13) "70.9379129944"
["TB23MEAN"]=>
string(3) "864"
["TB23STD"]=>
string(13) "92.7280971443"
}
}
genename xkr4
TA11MEAN 974.25
TA11STD 99.0085223605
TA21MEAN 710.75
TA21STD 115.79831605
TA22MEAN 736.5
TA22STD 115.79831605
TA23MEAN 903.75
TA23STD 107.283211641
TB11MEAN 799.25
TB11STD 97.2660655111
TB21MEAN 658
TB21STD 91.7959694104
TB22MEAN 592.75
TB22STD 70.9379129944
TB23MEAN 864
TB23STD 92.7280971443
This is how your data looks like from database it is a array of rows row is a object
I solved it:
<?php
$search_value=$_POST["search"];
$mysqli = new mysqli('localhost','root','password','mydb');
$myArray = array();
if ($result = $mysqli->query("SELECT * FROM transcriptome WHERE genename LIKE '%$search_value%'")) {
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$myArray = $row;
}
//file_put_contents('jsonoutput.json', json_encode($myArray));
$json = json_encode($myArray);
$array = json_decode($json, true);
$new_array = array();
foreach( $array as $key => $value ){
$newarray[] = array($key=>$value);
}
echo json_encode($newarray);
file_put_contents('jsonoutput.json', json_encode($newarray));
}
$result->close();
$mysqli->close();
?>

Adding RestAPI response to MySQL database

$cn = curl_init();
$url = 'https://URL';
curl_setopt($cn, CURLOPT_URL, $url);
curl_setopt($cn, CURLOPT_RETURNTRANSFER, TRUE);
$output = curl_exec($cn);
$aOutput = json_decode($output, TRUE);
//var_dump($aOutput);
$curl_error = curl_error($cn);
print_r($curl_error);
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
foreach($aOutput as $key => $data) {
var_dump($key['average_price']);
// var_dump($data[$key]["Average_Price"]);
// $sql = "INSERT INTO Market('type_id', 'average_price', 'adjusted_price')
// VALUES ($data);";
}
array(10763) {
[0]=>
array(3) {
["average_price"]=>
float(381907.23)
["adjusted_price"]=>
float(383184.18)
["type_id"]=>
int(32772)
}
[1]=>
array(3) {
["average_price"]=>
float(54090.07)
["adjusted_price"]=>
float(57340.16)
["type_id"]=>
int(32774)
}
I am attempting to add this entire multidimensional array to my database. The main thing I am having trouble with is the foreach loop.
I have tried $array[$key][$column], and many other ways but I only get NULL when dumping the variable.
I have attempted, $key['average_price'] etc still returns null.
You're getting $key and $data muddled up.
Easiest if you annotate it out:
If your $aOutput array is
array(10763) {
[0]=>
array(3) {
["average_price"]=>float(381907.23)
["adjusted_price"]=>float(383184.18)
["type_id"]=>int(32772)
}
[1]=>
array(3) {
["average_price"]=>float(54090.07)
["adjusted_price"]=>float(57340.16)
["type_id"]=>int(32774)
}
....
then
foreach($aOutput as $key => $data) {
// $key = 0
// $data = array(3) {
["average_price"]=>float(381907.23)
["adjusted_price"]=>float(383184.18)
["type_id"]=>int(32772)
}
// So what you want is $data['average_price']
You can simplify this by not even using hte key, just do
foreach($aOutput as $data) {
// $data = array(3) {
["average_price"]=>float(381907.23)
["adjusted_price"]=>float(383184.18)
["type_id"]=>int(32772)
}
// So what you want is $data['average_price']

not receiving any values from php server

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);
}
}

How the get line by line keys and values of one level JSON in PHP

I am receiving a JSON array from Javascript as a $_POST variable.
I want to get all variables and its values of the JSON. I tried to use json_decode with foreach like bellow but it did not work. my php code is
<?php
$string = $_POST['json'];
var_dump(json_decode($string, true));
foreach($string as $key => $value) {
echo $key . " : " . $value;
}
?>
my json is
[{"EXTAPP_ID":"9901","CATEGORY_ID":"10","LANGUAGE_CODE":"tr","CATEGORY_LANG_DESC":"TR AAA"},{"EXTAPP_ID":"9901","CATEGORY_ID":"10","LANGUAGE_CODE":"de","CATEGORY_LANG_DESC":"DE AAA"},{"EXTAPP_ID":"9901","CATEGORY_ID":"20","LANGUAGE_CODE":"de","CATEGORY_LANG_DESC":"DE XXX"},{"EXTAPP_ID":"9901","CATEGORY_ID":"20","LANGUAGE_CODE":"tr","CATEGORY_LANG_DESC":"TR YYY"},{"EXTAPP_ID":"9901","CATEGORY_ID":"10","LANGUAGE_CODE":"en","CATEGORY_LANG_DESC":"EN ZZZ"},{"EXTAPP_ID":"9901","CATEGORY_ID":"20","LANGUAGE_CODE":"en","CATEGORY_LANG_DESC":"EN VVV"}]
it returns the request as a array like bellow (I did not paste all result)
array(6) {
[0]=>
array(4) {
["EXTAPP_ID"]=>
string(4) "9901"
["CATEGORY_ID"]=>
string(2) "10"
["LANGUAGE_CODE"]=>
string(2) "tr"
["CATEGORY_LANG_DESC"]=>
string(19) "TR XXX"
}
[1]=>
array(4) {
["EXTAPP_ID"]=>
string(4) "9901"
["CATEGORY_ID"]=>
string(2) "10"
["LANGUAGE_CODE"]=>
string(2) "de"
["CATEGORY_LANG_DESC"]=>
string(17) "TR YYY"
}
[2]=>
what I expected was
EXTAPP_ID: 9901
CATEGORY_ID:10
LANGUAGE_CODE:de
CATEGORY_LANG_DESC:DE AAA
Decode the string with $string = json_decode($_POST['json'], true);
You can get desired result by following code
$string = $_POST['json'];
$string = json_decode($string, true);
foreach($string as $value) {
foreach($value as $k=>$v) {
echo $k . " : " . $v .'<br/>';
}
echo '<hr>';
}
Try this instead:
$string = json_decode($_POST['json'], true);
foreach($string as $key => $value) {
echo $key . " : " . $value;
}
Try this:
$string = $_POST['json'];
$data = json_decode($string, true);
var_dump($data);
foreach($data as $key => $value) {
echo $key . " : " . $value;
}

How to concat the echo output with some base URL in JSON

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.

Categories