Create json api for mobile application using php mysql - php

Hello I need to create a json encode api for the code which i am building
Currently my project have 3 tables item table,payment table and sms table
item table contains the details of my project and the item table is linked to payment and sms table
i am listing the json form which i want to make
{
"Data": {
"Projects": [{
"id": "10023",
"Info": "Arabic project info ",
"paymentMethods": {
"Bank": [{
"accname": "Zakat Acc",
"accnameEn": "حساب الزكــــــاة",
"country": "UAE",
"acc": "0034430430012"
}, {
"accname": "Zakat Acc",
"accnameEn": "حساب الزكــــــاة",
"country": "UAE",
"acc": "00344304332412"
}],
"SMS": [{
"operatorEn": "etisalat",
"shortcode": "4236",
"operator": "إتصالات"
}, {
"operatorEn": "etisalat",
"shortcode": "4346",
"operator": "إتصالات"
}],
"CC": {
"-URL":
"http://www.sharjahcharuty.org/donations/"
}
}
}, {
"id": "10026",
"Info": "Arabic project info ",
"InfoEn": "project info in english",
"paymentMethods": {
"Bank": [{
"accname": "Zakat Acc",
"accnameEn": "حساب الزكــــــاة",
"country": "UAE",
"acc": "0034430430012"
}, {
"accname": "Zakat Acc",
"accnameEn": "حساب الزكــــــاة",
"country": "UAE",
"acc": "00344304332412"
}],
"SMS": [{
"operatorEn": "etisalat",
"shortcode": "4236",
"operator": "إتصالات"
}, {
"operatorEn": "etisalat",
"shortcode": "4346",
"operator": "إتصالات"
}],
"CC": {
"-URL": "http://www.sharjha.org/donations/"
}
}
}]
}
}
I have created php code for the system
But this code i have create using brackets and seperated by queries but this system not giving the result what i expected
echo $string='{"Data":{';
//echo $string='"Projects":';
$sql2 = "SELECT * FROM wg_items where cat_id=6007;";
$query = $this->db->query($sql2);
echo $string='"Projects":';
echo $string='[';
$intcount=0;
$scateg="";
if ($query->num_rows() > 0) {
foreach ($query->result() as $row){
//$jsonrows[]=array("id"=>$row->cat_id,"name"=>$row->item_name);
echo $string='{';
echo $string = 'id:'.$row->item_id;
echo $string=',';
echo $string = 'name:'.$row->item_name;
echo $string=',';
//-------------------------------------------------------------//
$hasComma = false;
echo $string='"paymentmethods":';
echo $string='"Bank":[';
$sql2 = "SELECT * FROM paymentmethods where cid=587 ";
$query = $this->db->query($sql2);
foreach ($query->result() as $row){
echo '{';
echo $string = 'accname:'.$row->acc.',' ;
echo $string = 'country:'.$row->IBAN.',' ;
echo $string = 'Iban:'.$row->Bankname.',' ;
echo $string = 'Bankname:'.$row->Bankname.',' ;
echo $string = '},';
}
echo $string = '],';
echo $string='"SMS":[';
$sql3 = "SELECT * FROM sms where cid=537 ";
$query = $this->db->query($sql3);
$hasComma = false;
foreach ($query->result() as $rows){
echo '{';
echo 'Operator:'.$rows->operator.',' ;
echo 'shortcode:'.$rows->shortcode.',';
echo 'keyword:'.$rows->keyword.',';
echo 'price:'.$rows->price;
echo $string = '},';
if($hasComma = TRUE)
{
}
$hasComma = TRUE;
}
echo $string = '}],';
echo $string='"CC":{';
echo $string3='"-URL:"';
echo $string3='"HTTP:SHARJAHCHARTITY.COM"';
ECHO '}}}';
echo ',';
}
echo ']}}}';

You are not suppose to append strings to create a json string.
Create an array which holds the data and wrap it with json_encode() function
For ex:
<?php
$array_data=[];
$array_data['firstname']="Rafique";
$array_data['lastname']="Mohammed";
$array_data['email']="plus.arr#gmail.com";
// or any data which you want in json
$json_output=json_encode($array_data);
echo $json_output;
OUTPUT :
{"firstname":"Rafique","lastname":"Mohammed","email":"plus.arr#gmail.com"}
UPDATE 2 :
In your case
<?php
//.. your code
if ($query->num_rows() > 0) {
foreach ($query->result() as $row){
$jsonrows=array("id"=>$row->item_id,"name"=>$row->item_name);
$jsonrows["paymentmethods"]=array("Bank"=>[]);
$sql2 = "SELECT * FROM paymentmethods where cid=587 ";
$query = $this->db->query($sql2);
foreach ($query->result() as $row){
//convert bank as array
$jsonrows["paymentmethods"]["Bank"][] = array(
"accname"=>$row->acc,
"country"=>$row->IBAN,
"Iban"=>$row->Bankname,
"Bankname"=>$row->Bankname );
}
//DO IT FOR REST OF THE CODE

Related

foreach loop cant find values of json object and display on php page

I got some data in my data/clients.json file and I'm trying to reach for some of the keys and values and display them in my php file. It does not work and i can not figure out why.
My clients.json file looks like:
{
"data": {
"nikajakubec": {
"name": "nika",
"loans": {
"amount": "1000",
"reason": "for garden"
}
}
}
}
And my PHP file:
<?php
$sData = file_get_contents('data/clients.json');
$jData = json_decode($sData);
$jClient = $jData->data->$sUsername;
foreach ($jClient->loans as $jLoans) {
echo "
<div>
<div>Amount:$jLoans->loans-></div>
<div>Reason:$sUserName->reason</div>
</div>";
}
?>
Do like this:-
<?php
$json = '{
"data": {
"nikajakubec": {
"name": "nika",
"loans": {
"amount": "1000",
"reason": "for garden"
}
}
}
}';
$jData = json_decode($json);
foreach ($jData->data as $user) {
echo "
<div>
<div>Amount:". $user->loans->amount ."</div>
<div>Reason: ". $user->loans->reason ."</div>
</div>";
}
Output:- https://3v4l.org/8HPV5
The field reason it's actually nested inside the loans prop, not directly in the user.
so instead of
$sUserName->reason
just go
$jLoans->reason
And also go $jLoans->amount instead of $jLoans->loans->
Consider that when you cycle $jClient->loans you are going to work on each prop of loans, which are 'amount' and 'reason'

array com problema json multidimensional

I am trying to get a data that is in an array inside another array, I did a search by the forum and google and I made several attempts without success.
It seems like an easy catch but I'm breaking my head all day and I can not.
I'm leaving below my JSON code and my last attempt to pass to PHP.
Thankful.
CODE JSON:
{
"ordens_de_servico": [
{
"oser_numero_os": 23932944,
"oser_nome_solicitante": "ED PI - CAMPO MAIOR",
"oser_dt_abertura": "27/03/2018",
"oser_pontos_refer_endereco": null,
"oser_observ_reclamacao": null,
"oser_prioridade": null,
"servico": {
"serv_cod_servico": 60,
"serv_descr_servico": "CORTE POR DEBITO"
},
"cliente": {
"nome": "ANTONIO WELTON DA SILVA OLIVEIRA",
"telefone": " "
},
"unidade_consumidora": {
"unid_ident_uc": 10945024,
"logr_nome_logr_expandido": null,
"medidor": "A2006171",
"latitude": " -4.711808",
"longitude": "-41.793455"
},
"faturas": [
{
"total_fatura": "23.01"
},
{
"total_fatura": "17.88"
},
{
"total_fatura": "23.01"
},
{
"total_fatura": "21.9"
},
{
"total_fatura": "22.92"
}
]
}
]
}
CODE PHP
<?php
// Read JSON file
$json = file_get_contents('oss.json');
//Decode JSON
$json_data = json_decode($json,true);
//Print data
print_r($json_data);
$os = $json_data['ordens_de_servico'][0]['oser_numero_os']. PHP_EOL;
$data = $json_data['ordens_de_servico'][0]['oser_dt_abertura']. PHP_EOL;
$cod_serv = $json_data['ordens_de_servico']['servico'][0]['serv_cod_servico']. PHP_EOL;
$total_fatura = $json_data['ordens_de_servico']['faturas'][0]['total_fatura']. PHP_EOL;
echo $os."<p>";
echo $data."<p>";
echo $cod_serv."<p>";
echo $total_fatura."<p>";
?>
I tried looping unsuccessfully on the fatura
$json_data = json_decode($json,false);
foreach ( $json_data->ordens_de_servico as $valor){
echo 'FATURA:'.$valor->faturas->total_fatura."<p>".PHP_EOL;
echo PHP_EOL;
}
At a minimum, you are missing the [0] on these two lines:
$cod_serv = $json_data['ordens_de_servico']['servico'][0]['serv_cod_servico']. PHP_EOL;
$total_fatura = $json_data['ordens_de_servico']['faturas'][0]['total_fatura']. PHP_EOL;
They need to be:
$cod_serv = $json_data['ordens_de_servico'][0]['servico']['serv_cod_servico']. PHP_EOL;
$total_fatura = $json_data['ordens_de_servico'][0]['faturas'][0]['total_fatura']. PHP_EOL;
Example of looping through elements in arrays:
foreach($json_data['ordens_de_servico'] as $key => $value){
echo $value["oser_numero_os"];
foreach($json_data['ordens_de_servico'][$key]['faturas'] as $index => $row){
}
}

submenus in php using json

<?php
$jsondata = file_get_contents('js/brand.json');
$data = json_decode($jsondata, true);
$menuonesublinks = $data['menuonesublinks']['links'];
foreach ($menuonesublinks as $menu_sublink) {
?>
<?php
echo $menu_sublink['title'];
?>
<?php
}
?>
o/p i am getting : usa,uk
how can i get inside subcities of city values ("subcities":[{"city":"dubai"},{'city':"london"}])
brand.json
{
"menuonesublinks": {
"links": [
{
"title": "usa",
"subcities":[{"city":"dubai"},{'city':"london"}]
},
{
"title": uk
}
]
}
}
You need to change your foreach loop in the following way,
// your code
foreach ($menuonesublinks as $menu_sublink) {
echo $menu_sublink['title'];
if(array_key_exists('subcities', $menu_sublink)){
foreach($menu_sublink['subcities'] as $subcity){
// Now access subcities like this: $subcity['city']
}
}
}
Here's the relevant reference:
http://php.net/manual/en/function.array-key-exists.php

Getting data from PHP to JSON

So, I want to create dynamic donut chart, where the datas are from mySql database. But, the problem is in that chart, the datas get from JSON.
My question, how to use datas from PHP to be use for JSON datas. here're my progress so far :
<?php
$query_A = "SELECT COUNT(category) as catg FROM mydata ORDER BY category";
$result_A = mysql_query($query_A);
$query_B = "SELECT COUNT(category) as catg FROM mydata ORDER BY category";
$result_B = mysql_query($query_B);
//Print JSON
$prefix = '';
"[\n";
while ( $row_A = mysql_fetch_assoc( $result_A ) ) {
$prefix . " {<br>";
' "category": "' . "A" . '",' . "<br>";
' "value": ' . $row_A['catg'] . ',' . "<br>";
" }";
$prefix = ",\n";
}
while ( $row_B = mysql_fetch_assoc( $result_B ) ) {
$prefix . " {<br>";
' "category": "' . "B" . '",' . "<br>";
' "value": ' . $row_B['catg'] . ',' . "<br>";
" }";
$prefix = ",\n";
}
"\n]";
?>
And here're JSON datas from that donut chart :
<script type="text/javascript">
var chart = AmCharts.makeChart( "chartdiv", {
"type": "pie",
"theme": "light",
"dataProvider": [ {
"title": "New",
"value": 200
}, {
"title": "Returning",
"value": 9899
}, {
"title": "Back",
"value": 900
} ],
"titleField": "title",
"valueField": "value",
"labelRadius": 10,
"radius": "42%",
"innerRadius": "60%",
"labelText": "[[title]]",
"export": {
"enabled": true
}
} );
</script>
I want to use my mysql datas for that JSON datas. Thank you
There's a handy function called json_encode. Simply run your data through this function.
$json = json_encode($data); // returns a JSON string
By the way, have you tried googling for "PHP create JSON" or something similar? The time it took you to write this question, you would already have found a solution. Not to mention the time you wasted on trying to create the JSON yourself.
Just saying, you can save a lot of time by asking a search engine … you are usually not the first to have a particular problem.
I can't understand why there are two identical queries but that said.
<?php
$query_A = "SELECT COUNT(`category`) as 'catg' FROM `mydata` ORDER BY `category`";
$result_A = mysql_query( $query_A );
$query_B = "SELECT COUNT(`category`) as 'catg' FROM `mydata` ORDER BY `category`";
$result_B = mysql_query( $query_B );
if( $result_A ){
$data=array();
while ( $row_A = mysql_fetch_assoc( $result_A ) ) {
$data[]=array('category'=>'A', 'value'=>$row_A['catg'] );
}
$json_A=json_encode( $data );
}
if( $result_B ){
$data=array();
while ( $row_B = mysql_fetch_assoc( $result_B ) ) {
$data[]=array('category'=>'B', 'value'=>$row_B['catg'] );
}
$json_B=json_encode( $data );
}
?>
Then, in your javascript you could do this:-
var json_a=<?php echo $json_A;?>;
var json_b=<?php echo $json_B;?>;

JSON: extract image links from array, grab the images and store 'em locally

I created this function which grabs an external (Instagram) JSON every 1000s, stores it locally and uses it to display some info.
<?php
function get_instagram($user_id=XXX,$count=80,$width=100,$height=100,$token="XXXXX"){
global $upload_dir;
$url = 'https://api.instagram.com/v1/users/'.$user_id.'/media/recent/?access_token='.$token.'&count='.$count;
$cache = $upload_dir['basedir'].'/json/instagram/'.sha1($url).'.json';
$i = 0;
if(file_exists($cache) && filemtime($cache) > time() - 1000){
$jsonData = json_decode(file_get_contents($cache), true);
} else {
$jsonData = json_decode(file_get_contents($url), true);
file_put_contents($cache,json_encode($jsonData));
}
$result = '<div id="instagram">'.PHP_EOL;
foreach ($jsonData['data'] as $value) {
$title = (!empty($value['caption']['text']))?' '.$value['caption']['text']:'...';
$location = (!empty($value['location']['name']))?' presso '.$value['location']['name']:null;
$caption = '<div style="display: none;">'.htmlentities($title, ENT_QUOTES, "UTF-8").'<br><em style="font-size:11px">Scattata il '.htmlentities(strftime('%e %B %Y alle %R', $value['caption']['created_time'])).' '.htmlentities($location).' (<a target="_blank" style="color:darkgrey" rel="nofollow" href="http://maps.google.com/maps?q='.htmlentities($value['location']['latitude']).',+'.htmlentities($value['location']['longitude']).'">mappa</a>)</em></div>';
if($i==6) {
$result .= '<a style="display:none" class="fancybox" data-fancybox-group="gallery" href="'.$value['images']['standard_resolution']['url'].'"></a> '.$caption.PHP_EOL;;}
else {
$result .= "\t".'<a class="fancybox" data-fancybox-group="gallery" href="'.$value['images']['standard_resolution']['url'].'"><img id="thumb'.++$i.'" src="'.$value['images']['low_resolution']['url'].'" alt="'.$value['caption']['text'].'" width="'.$width.'" height="'.$height.'" /></a> '.$caption.PHP_EOL;}
}
$result .= '</div>'.PHP_EOL;
return $result;
}
echo get_instagram();
?>
This is an example of how the JSON is composed (one entry only):
{
"pagination":{
"next_url":"https:\/\/api.instagram.com\/v1\/users\/15203338\/media\/recent?access_token=15203338.3d61d31.705be3b7805a412ebd10d05196ea57cf\u0026count=1\u0026max_id=618767037278465762_15203338",
"next_max_id":"618767037278465762_15203338"
},
"meta":{
"code":200
},
"data":[
{
"attribution":null,
"tags":[
],
"type":"image",
"location":{
"latitude":41.897323268,
"name":"Porta San Lorenzo",
"longitude":12.511488861,
"id":4798584
},
"comments":{
"count":0,
"data":[
]
},
"filter":"X-Pro II",
"created_time":"1387982800",
"link":"http:\/\/instagram.com\/p\/iWTVePtC7i\/",
"likes":{
"count":2,
"data":[
{
"username":"mozgyal",
"profile_picture":"http:\/\/images.ak.instagram.com\/profiles\/profile_855320445_75sq_1388054204.jpg",
"id":"855320445",
"full_name":"mozgyal"
},
{
"username":"lidia_rz",
"profile_picture":"http:\/\/images.ak.instagram.com\/profiles\/profile_283508926_75sq_1377609787.jpg",
"id":"283508926",
"full_name":"Lidiarizzi"
}
]
},
"images":{
"low_resolution":{
"url":"http:\/\/distilleryimage7.s3.amazonaws.com\/592551106d7311e39b0b120baf64fd93_6.jpg",
"width":306,
"height":306
},
"thumbnail":{
"url":"http:\/\/distilleryimage7.s3.amazonaws.com\/592551106d7311e39b0b120baf64fd93_5.jpg",
"width":150,
"height":150
},
"standard_resolution":{
"url":"http:\/\/distilleryimage7.s3.amazonaws.com\/592551106d7311e39b0b120baf64fd93_8.jpg",
"width":640,
"height":640
}
},
"users_in_photo":[
],
"caption":{
"created_time":"1387982800",
"text":"Pappa",
"from":{
"username":"multiformeingegno",
"profile_picture":"http:\/\/images.ak.instagram.com\/profiles\/profile_15203338_75sq_1323624047.jpg",
"id":"15203338",
"full_name":"Lorenzo"
},
"id":"618767037731450618"
},
"user_has_liked":false,
"id":"618767037278465762_15203338",
"user":{
"username":"multiformeingegno",
"website":"",
"profile_picture":"http:\/\/images.ak.instagram.com\/profiles\/profile_15203338_75sq_1323624047.jpg",
"full_name":"Lorenzo",
"bio":"",
"id":"15203338"
}
}
]
}
How can I grab the images (standard_resolution and low_resolution for example), store them locally and use those instead of the remote ones?
Given that json data you provided is one entry.
//foreach entry as $jsonData
$ret = json_decode($jsonData, true);
$ret = $ret['data'];
$ret = $ret['images'];
$low_res = $ret['low_resolution'];
$stand_res = $ret['standard_resolution'];
//do some database stuff to save it.
//on to the next one
//end foreach
Haven't tested, so hope it works :-)

Categories