This works when we do this:
$db = $connection->messages;
$collection = $db->messagesCollection;
$messageArray = $collection->find(array('IDto' => '4'));
foreach($messageArray as $messageData){
$messageFrom = $messageData['IDfrom'];
$messageTo = $messageData['IDto'];
$messageTitle = $messageData['messageTitle'];
$messageIfRead = $messageData['ifRead'];
}
$JSONData = array('true', $messageFrom, $messageTo, $messageTitle, $messageIfRead);
echo $_GET['callback']."(".json_encode($JSONData).")";
But when we do this:
$db = $connection->messages;
$collection = $db->messagesCollection;
$messageArray = $collection->find(array('IDto' => '4'));
$JSONData = array('true', $messageArray);
echo $_GET['callback']."(".json_encode($JSONData).")";
and in the Javascript do this:
$.getJSON("mySite.com/pullData/getMail.php?callback=?",{
request: requestVar},
function(recievedData) {
alert(recievedData);
})
We get an alert of true, [object Object]
When using console log we get Object {}
How do we send that table data correctly?
I believe your biggest problem is the MongoCursor:
$messageArray = $collection->find(array('IDto' => '4'));
$JSONData = array('true', $messageArray);
echo $_GET['callback']."(".json_encode($JSONData).")";
You are trying to encode an object of MongoCursor there, hence the string representation is [object Object].
Try:
$messageArray = $collection->find(array('IDto' => '4'));
$JSONData = array('true', iterator_to_array($messageArray));
echo $_GET['callback']."(".json_encode($JSONData).")";
Instead. All find functions in MongoDB return a MongoCursor, the reason why your first code works is because you iterate the cursor building up your objects:
foreach($messageArray as $messageData){
$messageFrom = $messageData['IDfrom'];
$messageTo = $messageData['IDto'];
$messageTitle = $messageData['messageTitle'];
$messageIfRead = $messageData['ifRead'];
}
Note as well that the default json_encode of a document will contain objects, such as MongoId and MongoDate that do not encode too well into reusable JSON syntax. As such you will need to handle these types yourself.
Edit
Maybe a better way is to actually redo the indexes manually:
$messageArray = $collection->find(array('IDto' => '4'));
$d = array();
foreach($messageArray as $row){
$d = $row;
}
$JSONData = array('true', $d);
echo $_GET['callback']."(".json_encode($JSONData).")";
This way you will have a 0 based incrementing index instead of the ObjectId as each index base.
Related
I have a PHP code that converts a JSON into an array of two elements.
{"object":"card","id":"card_1"}
But when I try to print the both, the first returns the value and the second only the boolean.
echo 'id = ' . $response["id"];
echo 'object = ' .$response["object"];
Getting this:
id = true
object = card
What is wrong?
It seems, that you use json_decode to convert your JSON data to an array. Use next basic example to get your expected data:
<?php
// Input
$json = '{"object":"card","id":"card_1"}';
$array = json_decode($json, true);
// Specific items
echo 'id = '.$array["id"].'<br>';
echo 'object = '.$array["object"].'<br>';
// All items
foreach($array as $key => $value) {
echo $key.": ".$value."<br>";
}
?>
Could you please provide the code you use to convert this JSON into an array ?
This works fine:
$jsonObject = '{"object":"card","id":"card_1"}';
$decodedObject = json_decode($jsonObject);
$object = $decodedObject->object;
$id = $decodedObject->id;
echo "Object: {$object}, ID: {$id}";
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.
I read user from the database but I return json to ajax only return the last user because I cant concatenate the json encode.
$myObj = new \stdClass();
while ($fila = $bd->fila()) {
$myObj->NOMBRE = $fila["NOMBRE"];
$myObj->ROLENAME = $fila["ROLENAME"];
$myObj->IDUSER = $fila["IDUSER"];
$myJSON = json_encode($myObj);
}
echo $myJSON;
You are now overwriting $myJson in each iteration. We can also not "concatanate" two jsons (well, we could, but we shouldn't, cause it's laborious..).
Better put everything in one array/object and json_encode() at the very end.
$myObj = new \stdClass();
$users = array(); // instantiate a new array
while ($fila = $bd->fila()) {
$myObj->NOMBRE = $fila["NOMBRE"];
$myObj->ROLENAME = $fila["ROLENAME"];
$myObj->IDUSER = $fila["IDUSER"];
// add objects to that array
$users[] = $myObj;
}
// then at the end encode the whole thing to json:
echo json_encode($users);
Now here are some variants:
If you want everything that your db is returning in this items you could shorten that to:
$users = array(); // instantiate a new array
while ($fila = $bd->fila()) {
// add the whole item (cast as Object) to that array
$users[] = (Object) $fila;
}
// then at the end encode the whole thing to json:
echo json_encode($users);
If you don't care if the items are objects or arrays you could skip the casting and just add the array to the big array:
$users[] = $fila;
Maybe if you concatenate it as array like this
$myJSON[] = $myObj;
and then after the while
echo json_encode($myJSON);
You just have to collect data to big array and then encode whole array. Also there's no reason for creating new StdObjects instead of usual arrays.
// define empty array
$result = [];
while ($fila = $bd->fila()) {
// add to the array all needed elements one by one
$result[] = [
'NOMBRE' => $fila["NOMBRE"],
'ROLENAME' => $fila["ROLENAME"],
'IDUSER' => $fila["IDUSER"],
];
}
// encode whole result
echo json_encode($result);
I'm on PHP and I need to edit a JSON output to return only objects >=0 and divided by one hundred
Eg.
$json = {"data":[0,55,78,-32,-46,37]}
Needed
$json = {"data":[0,0.55,0.78,0.37]}
How this can be done?
Well, I know this is not the best practice, but if it's as simple as this, you can do the following.
$json = '{"data":[0,55,78,-32,-46,37]}';
// decoding the string to objects & arrays
$x = json_decode($json);
// applying a function on each value of the array
$x->data = array_map(
function($a)
{
if( $a >= 0 ) return $a/100;
else return null;
},
$x->data
);
// Removing empty values of the array
$x->data = array_filter($x->data);
// making a JSON array
$jsonData = json_encode(array_values($x->data));
// inserting a JSON array in a JSON Object
$json = '{"data":' . $jsonData . '}';
// here is your {"data":[0,0.55,0.78,0.37]}
echo $json;
Hope it helps !
Btw, I had to trick the json encode with array_values to prevent the creation of an object rather than an array for the data content. But I guess there is a better method that I just don't know ...
EDIT :
Find out the way :D
Once empty values removed from the array, just do :
$x->data = array_values($x->data);
$json = json_encode($x);
This will do the trick and it will not create issues with the rest of the object.
Alessandro:
Here's my approach, feel free to try. json_decode and a simple foreach can help you...
Code:
$json = array();
$result = array();
$json = '{"data":[0,55,78,-32,-46,37]}';
$decoded_json=json_decode($json, TRUE);
foreach ($decoded_json['data'] as &$value) {
if ($value >= 0){
$value = $value / 100;
$result[]=$value;
}
}
echo json_encode($result);
?>
Result:
[0,
0.55,
0.78,
0.37
]
I have successfully get content from the database and output the results in JSON. But I want to add a text that doesn't exists in the database and it's here I'm stuck.
$statement = $sql->prepare("SELECT data_filename,
data_filetype,
data_uniqid,
data_description,
data_coordinates,
exif_taken,
exif_camera,
exif_camera_seo,
exif_resolution,
exif_sensitivity,
exif_exposure,
exif_aperture,
exif_focallength,
is_downloadable,
is_notaccurate,
allow_fullsize
FROM photos
WHERE data_filename = 'P1170976'");
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo $json;
That code gives me
[{"data_filename":"P1170976","data_filetype":"JPG","data_uniqid":"","data_description":"","data_coordinates":"","exif_taken":"0000-00-00","exif_camera":"","exif_camera_seo":"","exif_resolution":"","exif_sensitivity":"0","exif_exposure":"","exif_aperture":"","exif_focallength":"","is_downloadable":null,"is_notaccurate":null,"allow_fullsize":null}]
Which is correct of course but if I add these 2 new lines under $json = json_encode... I'm getting null.
$newdata = array('test' => 'just testing');
$json[] = $newdata;
What have I done wrong here?
json_encode() returns a string, so you can’t handle it as an array, i.e. add elements to string.
As noted in comments, you need to add those lines before json_encode() or decode it back to array using json_decode(), then apply the lines and then back json_encode().
Example about usage of json_encode and json_decode:
$array = array("this" => array("will" => array("be" => "json")));
$string = json_encode($array); // string(31) "{"this":{"will":{"be":"json"}}}"
// ...
$array2 = json_decode($string); // now it’s same array as in first $array
$array2["new"] = "element";
$string2 = json_encode($array2);
var_dump($string2); // string(46) "{"this":{"will":{"be":"json"}},"new":"string"}"
Try this:
$newdata = array('test' => 'justtesting');
$results[] = $newdata;
$json = json_encode($results);
or if you definately need it after its encoded:
$json = json_encode($results);
//lots of stuff
$jarray = json_decode($results, true);
$newdata = array('test' => 'justtesting');
$jarray[] = $newdata;
$json = json_encode($jarray);