android, php, parsing JSON in php file sent from android - php

i have this JSON
{
"count":"3",
"num":"1",
"array":[
{
"id":"a_a",
"amount":56,
"duration":"0:12",
"time":1234566,
"type":0
},
{
"id":"a_a",
"amount":56,
"duration":"0:12",
"time":1234566,
"type":1
}
]
}
created it in android and send it by **HttpPost**
, i've tried a lot of ways to get the data in the php, my php file is this:
<?php
$response = array();
//$json_data = json_encode(stripslashes($_POST['jsonarray']))
$josn = file_get_contents("php://input");
$json_data = json_decode($josn,true);
$count = $json_data->{'count'};
$num = $json_data["num"];
$response["data"]=$count;
$response["data2"]=$num;
// echoing JSON response
echo json_encode($response);
?>
but $count and $num always returns null, any help please, and thanks.

$json_data = json_decode($josn,true);
this returns an array, not an object (which you are using later in the code). Use this to convert the json string to an object:
$json_data = json_decode($josn);
Or you could just use arrays, in which case your code should look like:
<?php
$response = array();
//$json_data = json_encode(stripslashes($_POST['jsonarray']))
$josn = file_get_contents("php://input");
$json_data = json_decode($josn, true); // using true to get array
$count = $json_data["count"]; // accessing array values as normal
$num = $json_data["num"]; // accessing array values as normal
$response["data"] = $count; // instead of setting $count first you could just add
$response["data2"] = $num; // the json_data array values directly to the response array
// echoing JSON response
echo json_encode($response);

Related

Append php loop data to JSON object

I need looped php data in an html template so I know it has something to do with JSON however not a JSON expert and cannot find much help in searching the web.
$uniqueFranchise_id = array_unique($franchise_id);
$dataArr = '[
{
"name": "Dylan",
"page_link": "https://mypage.com/"
}
]';
foreach($uniqueFranchise_id as $franchise)
{
$sqlFranchise = "select * from franchise where franchise_id = $franchise";
$resultFranchise = $conn->query($sqlFranchise);
if($resultFranchise->num_rows > 0)
{
while($rowFranchise = $resultFranchise->fetch_assoc())
{
$dataArr = json_decode($data, TRUE);
$dataArr[] = "['name'=>'".$rowFranchise['name']."', 'page_link'=>'".$rowFranchise['page_link']."']";
//$json = json_encode($dataArr);
}
}
}
$json = json_encode($dataArr);
print_r($dataArr);
But it only appends one row. In fact it deleteds that data that's already in my dataArr and just adds one row from my loop? Maybe I'm approaching this situation completely wrong?
You set your $dataArr inside the while-loop. So each time the loop is runs, it will be overwritten. Also, it makes more sense and it's much more clear when you handle it as an array (or object) and afterwards convert it to JSON.
$dataArr = array(array('name' => 'Dylan', 'page_link' => 'https://mypage.com/'));
foreach($uniqueFranchise_id as $franchise)
{
$sqlFranchise = "select * from franchise where franchise_id = $franchise";
$resultFranchise = $conn->query($sqlFranchise);
if($resultFranchise->num_rows > 0)
{
while($rowFranchise = $resultFranchise->fetch_assoc())
{
$dataArr[] = array('name' => $rowFranchise['name'], 'page_link' => $rowFranchise['page_link']);
}
}
}
$json = json_encode($dataArr);
echo $json;
You shouldn't be building the string up by yourself, you should build the data and then JSON encode the result (comments in code)...
$dataArr = '[
{
"name": "Dylan",
"page_link": "https://mypage.com/"
}
]';
// decode existing JSON to start array
$dataArr = json_decode($data, TRUE);
foreach($uniqueFranchise_id as $franchise)
{
// Read just the data you need from the table
$sqlFranchise = "select name, page_link from franchise where franchise_id = $franchise";
$resultFranchise = $conn->query($sqlFranchise);
if($resultFranchise->num_rows > 0)
{
// Read all of the rows into an array
$newData = $resultFranchise->fetch_all(MYSQLI_ASSOC);
// Add in existing data
$dataArr = array_merge($dataArr, $newData);
}
}
// Now encode the list of elements into 1 string
echo json_encode($dataArr);
You should also look into prepared statements if this data is not trusted to stop SQL injection.

How to get multiple array JSON Data

I have Json Data with multiple array, and i try to get the data inside effect_property, but it keep return nothing.
Here is my code
$json = file_get_contents('data.json');
$json_data = json_decode($json,true);
for($i = 0; $i < $count_data_action; $i++){
$path_data_action = $json_data[t03_action][data][$i][effect_property];
}
when i print the $path_data_action it show something like this:
{"duration":1,"delay":0,"propTo":{"source":"image","source_path":"../uploads/17041409353289557288/","source_file":"1704141604180616.jpg","source_name":"image1.jpg"},"beforeAction":"0","action_order":"1"}
How can i get the source_path?
Probably the JSON you are decoding with :
$json_data = json_decode($json,true);
contains another JSON string at key effect_property. You could change that to JSON Object and it should work fine.
Otherwise, you could use json_decode again, like :
for($i = 0; $i < $count_data_action; $i++){
$path_data_action = $json_data[t03_action][data][$i]effect_property];
$pathDataActionArr = json_decode($path_data_action , true);
$sourcePath = $pathDataActionArr['propTo']['sourcePath'];
}
Furthermore, to know any last occurred error with JSON encoding/decoding
json_last_error — Returns the last error occurred
UPDATE : I tried to decode the JSON you posted with code :
$fileContent = file_get_contents("/home/tarun/Desktop/test/abcd");
$jsonArray = json_decode($fileContent,true);
var_dump($jsonArray['t03_action']['data'][9]['effect_property']);
$effectPropertyArr = json_decode($jsonArray['t03_action']['data'][9]['effect_property'],true);
if(isset($effectPropertyArr['propTo']['source_path'])) {
var_dump($effectPropertyArr['propTo']['source_path']);
} else {
var_dump("No such key!");
}
Here, not all your elements of the array at key effect_property contains source_path. That's why :
if(isset($effectPropertyArr['propTo']['source_path'])) {
The above is working fine, with output :
/home/tarun/Desktop/test/temp.php:6:
string(205) "{"duration":1,"delay":0,"propTo":{"source":"image","source_path":"../uploads/18032022375907620062/","source_file":"1804100413270066.jpg","source_name":"Penguins.jpg"},"beforeAction":"0","action_order":"1"}"
/home/tarun/Desktop/test/temp.php:10:
string(32) "../uploads/18032022375907620062/"
// decoded array passed key of that array
$json_data['propTo']['source_path'];
try this ,Its working for me.
var data = {"duration":1,"delay":0,"propTo":{"source":"image","source_path":"../uploads/17041409353289557288/","source_file":"1704141604180616.jpg","source_name":"image1.jpg"},"beforeAction":"0","action_order":"1"}
alert(data.duration);
var Prop = data.propTo;
alert(Prop.source_path);`enter code here`

how can produce json array with while in php

i want return my data from mysql to json array with do while loop.
when i return one record with json it is well. but i want return list of array in one json array.
how can do that with index in while? my code have error and i don't know how can do it. with one record it is well but more can't.
$json="array(";
do{
$json=."'$row_query['id']'=>array('fname'=>$row_query['fname'],'lname'=>$row_query['lname']),";
} while ($row_query = mysqli_fetch_assoc($query));
json=.")";
echo json_encode($json,JSON_UNESCAPED_UNICODE);
There's no need to add quotes, brackets, parentheses or whatever. json_encode function will do it for you. Just provide an array to it:
$json = [];
while ($row_query = mysqli_fetch_assoc($query)) {
$json[$row_query['id']] = [
'fname'=>$row_query['fname'],
'lname'=>$row_query['lname'],
];
}
echo json_encode($json,JSON_UNESCAPED_UNICODE);
This is the most super easy version. You may try this.
$json = new array();
do{
array_push($json,$row_query);
} while ($row_query = mysqli_fetch_assoc($query));
or
$json = [];
do{
$json[] = $row_query;
} while ($row_query = mysqli_fetch_assoc($query));
Atlast encode your json variable.
$json = json_encode($json);
echo $json;

PHP: Unable to echo values from nested Array in PHP

I want to echo data which is in JSON format. I converted from JSON to PHP array using json_decode() but it is not getting echoed. Blow is my code:
<?php
$url = "http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&format=json&explaintext&titles=google";
//retriving JSON data using get_file_contents
$json = file_get_contents($url);
$data = json_decode($json);
$pageid = $data->query->pageids[0];
echo $data->query->pages->$pageid->extract;
?>
I only needed extract data which contains information for that title.
If you run the request in the browser, you will see that the returned JSON does not contain a pageids property, but is of the form
{
"batchcomplete": "",
"query": {
"normalized": [
...
],
"pages": {
...
}
}
}
If all you want is to grap the extract from the first item, you could do:
<?php
$url = "http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&format=json&explaintext&titles=google";
//retriving JSON data using get_file_contents
$json = file_get_contents($url);
$data = json_decode($json);
$page = reset($data->query->pages);
$extract = $page ? $page->extract : null;

Php JSONArray decoding and performing Database Operation

I'm sending a JsonArray from my android application as this:
final JSONArray data = new JSONArray();
try{
for(int i = 0; i<contactsList.size(); i++){
JSONObject jobj = new JSONObject();
ObjectContacts ob = contactsList.get(i);
jobj.put("contactid", ob.getContact_id());
jobj.put("mobile", ob.getNumber());
data.put(jobj);
}
}
And the resulting Array that my server receive.
[
{"contactid":"3","mobile":"(545) 454-5445"},
{"contactid":"1","mobile":"(880) 939-5212"},
{"contactid":"2","mobile":"822895456165"}
]
I need to fetch mobile numbers from this array and perform a Db Operation to look if this mobile number exist or not. How can I access each mobile and perform a Query? The query will consist of looking for mobile number existence and if it's true, it will fetch the name belonging to the mobile number and finally return an array back to the mobile application in JSONArray format which will consist of contact id, mobile, status(Yes or No), name.
Time won't be an issue but sometimes the array may contain 300-400 mobile number depending on user's contact.
Update
Here's the new Php Code that I implemented:
$app->post('/getcontacts', function () use ($app) {
//Verifying the required parameters
verifyRequiredParams(array('data'));
//Creating a response array
$response = array();
//reading post parameters
$data = $app->request->post('data');
$data_array = json_decode($data);
foreach ( $data_array as $obj ) {
$res = array();
$db = new DbOperation();
$r = $db->checkContactExist($obj->mobile);
if($r){
$res["contactid"] = $obj->contactid;
$res["mobile"] = $obj->mobile;
$res["name"] = $obj->name;
$res["status"] = 'yes';
$res["image_small"] = $db->getImageSmall($obj->mobile);
} else {
$res["contactid"] = $obj->contactid;
$res["mobile"] = $obj->mobile;
$res["name"] = $obj->name;
$res["status"] = 'no';
$res["image_small"] = '';
}
}
$response["error"] = false;
$response["message"] = json_encode($res);
echoResponse(201, $response);
});
The response I get from server:
{"contactid":"3","mobile":"(943) 101-9713","status":"no","image_small":""}
While there should be three contacts, it could only read one.
If I just send the incoming data back to application through echo to check whether all the contacts is coming or not, then it works correct. Maybe in the loop I'm adding detail about only one contact.
Second Update
Have solved the issue by putting :
$final_res = array();
and in foreach loop
$final_res[] = $res;
thus sending this back:
json_encode($final_res);
That string will convert to a PHP array of objects, after using json_decode() on the string.
So this is how you process it
<?php
$json_string = '[
{"contactid":"3","mobile":"(545) 454-5445"},
{"contactid":"1","mobile":"(880) 939-5212"},
{"contactid":"2","mobile":"822895456165"}
]';
$json_array = json_decode($json_string);
foreach ( $json_array as $obj ) {
echo $obj->contactid . ' - ' . $obj->mobile . PHP_EOL;
}
Result:
3 - (545) 454-5445
1 - (880) 939-5212
2 - 822895456165
You should be able to take this and add any database access around this simple code

Categories