formatted json format in php webservices - php

I am new in PHP. I am trying to format JSON. Here's the relevant code:
$query = mysql_query("SELECT *
FROM `micards` m
JOIN user u ON m.`mobile` = u.phone");
while ($row = mysql_fetch_assoc($query)) {
$response["success"] = 1;
$name = array('name'=>$row["name"],'email'=>$row["email"],'mobile'=>$row["mobile"]);
$phone[] = array('phone'=>$row["phone"],array('card'=>$name));
$response["contacts"] = $phone;
}
echo json_encode($response);
I'm getting this output:
{
"success": 1,
"contacts": [{
"phone": "919898989898",
"0": {
"card": {
"name": "abcd",
"email": "vwxy#test.com",
"mobile": "919898989898"
}
}
}, {
"phone": "919898989898",
"0": {
"card": {
"name": "abcd",
"email": "rstp#test.com",
"mobile": "919898989898"
}
}
}, {
"phone": "8686868686",
"0": {
"card": {
"name": "pan",
"email": "pnqr#gmail.com",
"mobile": "8686868686"
}
}
}, {
"phone": "8686868686",
"0": {
"card": {
"name": "monk",
"email": "abcd#gmail.com",
"mobile": "8686868686"
}
}
}]
}
But I want it to be:
{
"success": 1,
"contacts": [{
"phone": "919898989898",
{
"card": {
"name": "abcd",
"email": "vwxy#test.com",
"mobile": "919898989898"
}
},
{
"card": {
"name": "abcd",
"email": "rstp#test.com",
"mobile": "919898989898"
}
}
}],
[{
"phone": "8686868686",
{
"card": {
"name": "panky",
"email": "pnqr#gmail.com",
"mobile": "8686868686"
}
},
{
"card": {
"name": "panky",
"email": "abcd#gmail.com",
"mobile": "8686868686"
}
}
}]
}
What can I do to get the above output?

just change this part:
$phone[] = array('phone'=>$row["phone"],array('card'=>$name));
$response["contacts"] = $phone;
to
$response["contacts"][] = array('phone'=>$row["phone"],array('card'=>$name));

Just copy and paste this code
while ($row = mysql_fetch_assoc($query)) {
$response["success"] = 1;
$name = array('name'=>$row["name"],'email'=>$row["email"],'mobile'=>$row["mobile"]);
$response["contacts"][] = array('phone'=>$row["phone"],array('card'=>$name));
}

Please change
$phone[] = array('phone'=>$row["phone"],array('card'=>$name)) to
$phone[] = array('phone'=>$row["phone"],'card'=>$name)
;

My guess is that there is a problem with associative arrays and the way you are packing it. You can try to organize your response array like this:
$response = [
'success'=>1,
'contacts'=>[
'phone'=>$row['phone'],
'card'=>[
'name'=>$row['name'],
'email'=>$row['email'],
'mobile'=>$row['mobile']
]
]
];
It should work, didn't check it out thou.

Related

get array content from json (telegram api) in php

I have this json code
"result": [
{
"update_id": 74783732,
"message": {
"message_id": 852,
"from": {
"id": ---,
"is_bot": false,
"first_name": "---",
"username": "---",
"language_code": "en"
},
"chat": {
"id": ---,
"first_name": "---",
"username": "---",
"type": "private"
},
"date": 1646306224,
"text": "#username",
"entities": [
{
"offset": 0,
"length": 16,
"type": "mention"
}
]
}
}
]
I can get content from update_id , message, first_name etc.
but I want to get "mention" from type how can i do it?
my code is
here i decode json and get arrays from json and put them in variable and use it in my queries but I cant get mention from entities...
$update = file_get_contents("php://input");
$update_array = json_decode($update, true);
if( isset($update_array["message"]) )
{
$text = $update_array["message"]["text"];
$chat_id = $update_array["message"]["chat"]["id"];
}
if(isset($update_array["message"]["entities"]["type"]) and $update_array=="mention")
{
$get_username = $text;
show_users_by_username($get_username);
}
tnx for helping
$update_array will never be equal to "mention" but $update_array["message"]["entities"]["type"] yes.
Change your condition.

How to display info on double array JSON (php)

I would like to know how to display the information below.
Link (JSON):
https://my.callofduty.com/api/papi-client/ce/v1/title/bo4/platform/psn/match/11337378706913618925/matchMapEvents
What I wish to have:
"teams": [
[
{
"provider": "psn",
"username": "Germania1992"
},
{
"provider": "psn",
"username": "killzoneprofi"
},
{
"provider": "psn",
"username": "ayozetf87"
},
{
"provider": "psn",
"username": "Seith911"
},
{
"provider": "psn",
"username": "domibreu92"
}
],
[
{
"provider": "psn",
"username": "Thejuankarboy"
},
{
"provider": "psn",
"username": "Gamermad101"
},
{
"provider": "psn",
"username": "Izdrap"
},
{
"provider": "psn",
"username": "Guerra_sv"
},
{
"provider": "psn",
"username": "TriX_FollOoW_YT"
}
]
],
I want to display the nicks of the different teams
Example: Team 1 = Germania1992, killzoneprofi, ayozetf87, Seith911,
domibreu92
Thanks
You will have to do a double foreach that for sure.
<?php
// Get the json of the team
$team = team("https://my.callofduty.com/api/papi-client/ce/v1/title/bo4/platform/psn/match/11337378706913618925/matchMapEvents");
// Display the teams info
foreach($team as $nb=>$data){
echo "Team $nb<br />";
foreach($data as $key=>$value){
echo "Provider: ".$value->provider."<br />";
echo "Username: ".$value->username."<br />";
}
echo "<hr>";
}
// Returns the team array of the json
function team($jsonURL){
$content=file_get_contents($jsonURL);
$data=json_decode($content);
return $data->data->teams;
}
?>
You could increment the team number by 1 to avoid the first being 0
The above will display the below screenshot (You can format the output as you please)
$result = [];
$counter = 0;
dump($array = json_decode(file_get_contents('https://my.callofduty.com/api/papi-client/ce/v1/title/bo4/platform/psn/match/11337378706913618925/matchMapEvents')));
dump($t = array_column((array)$array, 'teams'));
foreach ($t as $r) {
foreach ($r as $p) {
$counter++;
foreach ($p as $value){
$result["team$counter"][] = $value->username;
}
}
}
var_dump($result);

php json foreach string value

I have a JSON file which contains some movie data:
[{
"title": "Bad Company",
"desc": "------------------------",
"rating": "6.0",
"image": "Psycho-Ex-Girlfriend-Twisted-2018.png",
"url": "master.m3u8",
"category": "اكشن"
}, {
"title": "The Pinch",
"desc": "------------------------",
"rating": "6.1",
"image": "Psycho-Ex-Girlfriend-Twisted-2018.png",
"url": "master.m3u8",
"category": "اكشن , جريمه"
}, {
"title": "Catskill Park",
"desc": "------------------------",
"rating": "6.2",
"image": "Psycho-Ex-Girlfriend-Twisted-2018.png",
"url": "master.m3u8",
"category": "خيال علمي , رعب"
}, {
"title": "Klippers",
"desc": "------------------------",
"rating": "5.3",
"image": "Psycho-Ex-Girlfriend-Twisted-2018.png",
"url": "master.m3u8",
"category": "اثاره , اكشن"
}, {
"title": "Psycho",
"desc": "------------------------",
"rating": "5.6",
"image": "Psycho-Ex-Girlfriend-Twisted-2018.png",
"url": "master.m3u8",
"category": "اثاره , دراما"
}]
I need to add all titles to a drop down menu, and when a user selects an item from the menu show the desc, image and category.
by php
Can anyone help me please?
my traying code
$url = 'http://localhost/ar.json';
$xx = json_decode(file_get_contents($url));
$data = json_decode($xx, true);
$search='title';
foreach($data['meta_data'] as $d){
if($d['key']==$search){
$found=$d['value'];
break;
}
}
echo $found?$found:"$search not found";
Assuming the structure, which you do not fully how us, is correct.
Use the key and value method of a foreach like this
$url = 'http://localhost/ar.json';
$xx = json_decode(file_get_contents($url));
$data = json_decode($xx, true);
$search='title';
$found = false;
foreach($data['meta_data'] as $key => $val){
if($key == $search){
$found = $val;
break;
}
}
echo $found ? $found : "$search not found";

Jotform: Parse returned data issue

I'm trying to parse data returned by the Jotform API.
I'm successfully echoing the data but I'm also getting unnecessary additional lines of text.
My PHP code is:
include "JotForm.php";
$jotformAPI = new JotForm("myapikey");
$submissions = $jotformAPI->getFormSubmissions("myformid");
var_dump($submissions );
foreach ($submissions as $data) {
$detail = $jotformAPI->getSubmission($data['id']);
foreach ($detail as $d) {
echo $d[1]['answer']['first'] . '<br>';
}
}
result of var_dump($submissions );
{
"responseCode": 200,
"message": "success",
"content": [{
"id": "237955080346633702",
"form_id": "31751954731962",
"ip": "123.123.123.123",
"created_at": "2013-06-25 03:38:00",
"updated_at": "2013-06-27 04:58:00",
"status": "ACTIVE",
"new": "1",
"answers": {
"1": {
"text": "Name",
"type":"control_fullname",
"answer": {
"first": "LeBron",
"last": "James"
},
"prettyFormat": "LeBron James"
},
"2": {
"text": "Your Message",
"type": "control_textarea",
"answer":"¡Ay, caramba!"
}
}],
}
And here is the result I'm getting:
1
0
0
0
C
0
LeBron
I had to repair your invalid json string...
Code: (Demo)
$json = '{
"responseCode": 200,
"message": "success",
"content": [{
"id": "237955080346633702",
"form_id": "31751954731962",
"ip": "123.123.123.123",
"created_at": "2013-06-25 03:38:00",
"updated_at": "2013-06-27 04:58:00",
"status": "ACTIVE",
"new": "1",
"answers": {
"1": {
"text": "Name",
"type":"control_fullname",
"answer": {
"first": "LeBron",
"last": "James"
},
"prettyFormat": "LeBron James"
},
"2": {
"text": "Your Message",
"type": "control_textarea",
"answer":"¡Ay, caramba!"
}
}}]
}';
foreach (json_decode($json, true)['content'] as $set) {
echo "{$set['answers'][1]['answer']['first']} {$set['answers'][1]['answer']['last']}\n";
}
Output:
LeBron James
I'm a little fuzzy on the action of the jot functions, but maybe it's supposed to be like this:
foreach ($submissions as $data) {
$detail = $jotformAPI->getSubmission($data['id']);
echo $detail['answers'][1]['answer']['first'] . '<br>';
}

Php xml data to json encode in specific format

This is my php file code where i am fetching data from thecatapi
i needed the specific format for datatable
$xml=file_get_contents('https://thecatapi.com/api/images/get?format=xml&results_per_page=3');
$xml = new SimpleXMLElement($xml);
$datas=array();
$datas['rows'] = $xml->data->images;
echo json_encode($datas, true);
Output is:
{"total":50,
"rows":{"image":[
{"url":"https:\/\/thecatapi.com\/api\/images\/get.php?id=e0i",
"id":"e0i",
"source_url":"http:\/\/thecatapi.com\/?id=e0i"
},
{"url":"https:\/\/thecatapi.com\/api\/images\/get.php?id=MTYwNDE0MQ",
"id":"MTYwNDE0MQ",
"source_url":"http:\/\/thecatapi.com\/?id=MTYwNDE0MQ"
},{
"url":"https:\/\/thecatapi.com\/api\/images\/get.php?id=bon",
"id":"bon",
"source_url":"http:\/\/thecatapi.com\/?id=bon"
}
]
}
}
but i wanted in this json form
{
"total": 800,
"rows": [
{
"url": 0,
"id": "Item 0",
"source_url": "$0"
},
{
"url": 0,
"id": "Item 0",
"source_url": "$0"
},
{
"url": 0,
"id": "Item 0",
"source_url": "$0"
},
Just came up with an alternativ solution. Change this line:
$datas['rows'] = $xml->data->images;
to this:
$datas['rows'] = $xml->data->images->image;
otherwise you can still do this
Decode the json string into an object and modify it suit your needs.
$stdClassObject = json_decode($jsonData);
$stdClassObject->rows = $stdClassObject->rows->image;
$newJsonData = json_encode($stdClassObject, JSON_PRETTY_PRINT);
echo '<pre>';
print_r($newJsonData);
echo '</pre>';
New output:
{
"total": 50,
"rows": [
{
"url": "https:\/\/thecatapi.com\/api\/images\/get.php?id=e0i",
"id": "e0i",
"source_url": "http:\/\/thecatapi.com\/?id=e0i"
},
{
"url": "https:\/\/thecatapi.com\/api\/images\/get.php?id=MTYwNDE0MQ",
"id": "MTYwNDE0MQ",
"source_url": "http:\/\/thecatapi.com\/?id=MTYwNDE0MQ"
},
{
"url": "https:\/\/thecatapi.com\/api\/images\/get.php?id=bon",
"id": "bon",
"source_url": "http:\/\/thecatapi.com\/?id=bon"
}
]
}

Categories