json_encode does not print the array name - php

I'm not experienced with json_encode and am trying to return an arrray of array which should be called aaData - for DataTables with server-side processing.
The output should be like:
{
"sEcho": 3,
"iTotalRecords": 57,
"iTotalDisplayRecords": 57,
"aaData": [
[
"Gecko",
"Firefox 1.0",
"Win 98+ / OSX.2+",
"1.7",
"A"
],
[
"Gecko",
"Firefox 1.5",
"Win 98+ / OSX.2+",
"1.8",
"A"
],
...
]
}
but the actuall output of my PostgreSQL 8.4-driven PHP-script
if (isset($_REQUEST['json'])) {
$aaData = array();
while ($row = $sth->fetch(PDO::FETCH_NUM)) {
array_push($aaData, $row);
}
print json_encode($aaData);
}
is actually missing outside brackets (object like?) and the aaData name:
[
[ .... ],
[ .... ],
[ .... ]
]
How would you do this best?

Another option is to use the code in the question but change one line:
print json_encode(array('aaData' => $aaData));

If you want it to have aaData as the name, then you'll need to give your array an associative index, like so:
if (isset($_REQUEST['json'])) {
$arr['aaData'] = array();
while ($row = $sth->fetch(PDO::FETCH_NUM)) {
array_push($arr['aaData'], $row);
}
print json_encode($arr);
}

To explain the root of your problem: The name of the variable, $aaData, has nothing to do with the data itself. Thus, json_encode does not serialize it.

Related

How to correctly encode and decode geoJson that contains both arrays and objects in php

How do I correctly decode geoJson that contains both arrays and strings in php.
The problem I have is reading it from the database and converting back to json, the coordinates arrays are missing.
I am currently reading it from a (valid) geoJson.json file and storing it a mysql database using: $jsondata = json_decode($srcfile, true); Which works fine - it looks correct in the (mysql) database and still has the coordinates arrays intact.
The raw data looks like: (except there are 1000s of coordinates)
{
"type": "Feature",
"geometry": {
"coordinates": [
[
[
[
-64.59727115377405,
60.30061384178721
],
[
-64.52477086139639,
60.29980770242815
]
]
],
[
[
[
-64.59727115377405,
60.30061384178721
],
[
-64.52477086139639,
60.29980770242815
]
]
]
],
"type": "MultiPolygon"
},
"properties": {
"prov_type": "province",
"prov_code": "24",
"prov_name_fr": "Qu\u00e9bec",
"geo_point_2d": [
53.3945173679,
-71.7823138976
],
"prov_name_en": "Quebec",
"year": "2019",
"prov_area_code": "CAN"
}
}
When I extract it from the database and run json_encode($data) on it, the output looks like this - missing all the coordinates.
{
"type":"Feature",
"geometry":{
"coordinates":,
"type":"MultiPolygon"
},
"properties":{
"prov_type":"province",
"prov_code":"35",
"prov_name_fr":"Ontario",
"geo_point_2d":[50.4486575765,-86.0470011166],
"prov_name_en":"Ontario",
"year":"2019",
"prov_area_code":"CAN"
}
}
is there a better way to store it originally to make it easier to work with? (I'm using modx xpdo which does not seem to support the JSON database type in the model - it just converts it to longtext)
OR
what is the correct method of encoding it back into valid json with the coordinates intact?
UPDATED - Added import method
public function importGeodata()
{
// $srcfile = file_get_contents('/var/www/vhosts/mcgill.local/src/core/components/mcgill/data/provinces.json');
$srcfile = file_get_contents('/var/www/vhosts/mcgill.local/src/core/components/mcgill/data/us-states.json');
$jsondata = json_decode($srcfile, true);
// echo '<pre>';print_r($jsondata); echo '</pre>';
foreach($jsondata['features'] as $feature)
{
// $search = $feature['properties']['prov_name_en']; // FOR CANADA
$search = $feature['properties']['NAME']; // FOR USA
if(!$updateObj = $this->modx->getObject('CatalogStates', array('name' => $search)))
{
echo '<br>Could not find object: ' . $search;
}else{
echo '<br>Found object: '.$search;
$updateObj->set('feature', json_encode(array($feature)));
if(!$updateObj->save())
{
echo '<br>Error saving object: ' . $search;
}
}
}
return;
}
Retrieve data:
public function getGeoJson()
{
$criteria = $this->modx->newQuery('CatalogStates');
$criteria->where([
'id:IN' => array(1,2),
]);
if($states = $this->modx->getCollection('CatalogStates',$criteria)) // returns an array of objects
{
foreach($states as $state)
{
$feature = $state->get('feature');
$coordinates = $feature['geometry']['coordinates'];
print_r($coordinates); // this returns the coordinates array
echo json_encode($coordinates); // this returns nothing!?
}
}
}
Well, bizzarre, it was MODX that was screwing me... MODX uses double square braces to denote code that should be processes or included - i.e.
[[code_snippet_name]]
[[*include_chunk_name]]
etc.
when it saw the coordinates structure:
"coordinates": [
[
[
[
-64.59727115377405,
60.30061384178721
],
[
-64.52477086139639,
60.29980770242815
]
]
],
[
[
[
-64.59727115377405,
60.30061384178721
],
[
-64.52477086139639,
60.29980770242815
]
]
]
]
It basically interpreted it as:
"coordinates": [[ // try to run a code snip here
// run this code snip (and fail)
[[-64.59727115377405,60.30061384178721],
// give up trying to output anything till we find a matching closing brace
So the actual solution is to:
json_encode($feature, JSON_PRETTY_PRINT );

Remove the item from array based on child value on object

I've got the following data structure:
Array -> Object -> Array -> Object -> Object
[
{
"id":6834,
"contract_id":13,
"schedule_column_values":[
{
"id":34001,
"field_value":{
"id":324241,
"value":10,
"field":{
"id":1,
"signature":"ios"
}
}
},
{
"id":34001,
"field_value":{
"id":324241,
"value":10,
"field":{
"id":1,
"signature":"android"
}
}
}
]
}
]
What I'm trying to achieve is that if a field has the signature of "android", remove its grandparent object from schedule_column_values. Basically, if a signature is "android", the final data would look like this:
[
{
"id": 6834,
"contract_id": 13,
"schedule_column_values": [
{
"id": 34001,
"field_value": {
"id": 324241,
"value": 10,
"field": {
"id": 1,
"signature": "ios"
}
}
}
]
}
]
This is just an example but the structure is always the same and we always know what signature we're looking for. It could be anything other than android but we know the string we're looking for.
I've tried a nested foreach loop and tried unset but it doesn't seem to work. The other way is I've set a NULL to object value of schedule_column_values when the signature of field is matched, but I cannot have NULL in the object.
What would be a good way to filter out this structure?
This is a perfect use case for array_filter:
$filtered_array = [];
foreach($array as $grandparent){
$filtered_schedules = array_filter(
$grandparent->schedule_column_values,
function($item){
return $item->field_value->field->signature !== 'android';
}
);
$altered_grandparent = clone $grandparent;
$altered_grandparent->schedule_column_values = $filtered_schedules;
$filtered_array[] = $altered_grandparent;
}

How to get specific email data from json using php

In one of my applications I get a JSON format data from php. Which is as similar as the following:
{
"abc#mail.com": {
"RequestSessions": [
{
"StartAt": "2020-03-29T05:18:37.973618Z",
"RunTime": 292,
"Captcha": 3,
"TotalBidRequests": 40,
"TotalSearchRequests": 2831,
"TotalTradeRequests": 88
}
],
"ProfitSessions": [
{
"StartAt": "2020-03-29T13:56:11.8250985Z",
"Profit": 42598,
"EProfit": 3350,
"Coins": 55674,
"Ecoins": 28000
}
]
},
"adc#mail.com": {
"RequestSessions": [
{
"StartAt": "2020-03-29T05:18:37.973618Z",
"RunTime": 292,
"Captcha": 3,
"TotalBidRequests": 40,
"TotalSearchRequests": 2831,
"TotalTradeRequests": 88
}
],
"ProfitSessions": [
{
"StartAt": "2020-03-29T13:56:11.8250985Z",
"Profit": 42598,
"EProfit": 3350,
"Coins": 55674,
"Ecoins": 28000
}
]
}
}
From this response, I just need to fetch email to process further operations in my application. But I can't identify how to decode this using PHP json_decode()
Can anyone tell me how can I decode this using PHP and fetch only email from this response?
Thanks
In that JSON, the email addresses are the keys of the object - i.e. the names of the properties. If you decode the JSON into an associative array you can get those values using PHP's array_keys function:
$data = json_decode($json, true);
foreach (array_keys($data) as $key)
{
echo $key.PHP_EOL;
}
This outputs:
abc#mail.com
adc#mail.com
Demo: http://sandbox.onlinephpfunctions.com/code/d7890691a6baae9f9314c727a9ad0f6519214a10

How to get json format for monogo db object [duplicate]

I am using PHP to connect with MongoDB. My code is as follows.
// connect
$m = new MongoClient($con_string); // connect to a remote host at a given port
$db = $m->main;
$customers = $db->customer->find();
i want to return $customers collection as json document to my HTML. How can i do this?
You can do this two ways:
echo json_encode(iterator_to_array($customers));
or you can manually scroll through it:
foreach($customers as $k => $row){
echo json_encode($row);
}
Each of MongoDBs objects should have their __toString() methods correctly implemented to bring back the representation of the value.
This also will work. And you can customize your json as well.
$arr = array();
foreach($customers as $c)
{
$temp = array("name" => $c["name"], "phone" => $c["phone"],
"address" => $c["address"]);
array_push($arr, $temp);
}
echo json_encode($arr);
Other answers work, but it is good to know that the generated JSON will have the following form (in this example I use an hypothetical "name" field for your customers):
{
"5587d2c3cd8348455b26feab": {
"_id": {
"$id": "5587d2c3cd8348455b26feab"
},
"name": "Robert"
},
"5587d2c3cd8348455b26feac": {
"_id": {
"$id": "5587d2c3cd8348455b26feac"
},
"name": "John"
}
}
So in case you don't want the Object _id to be the key of each of your result objects you can add a false parameter to iterator_to_array.
Your code would be:
echo json_encode(iterator_to_array($customers, false), true);
This creates the same result as
$result = Array();
foreach ($customers as $entry) {
array_push($result, $entry);
}
echo json_encode($result, true);
which is an array of JSON objects
[
{
"_id": {
"$id": "5587d2c3cd8348455b26feab"
},
"name": "Robert"
},
{
"_id": {
"$id": "5587d2c3cd8348455b26feac"
},
"name": "John"
}
]

How to remove extra array from Json data in php

I want to remove Extra array from this JSON "data".
how to do this in PHP. Is it any function in PHP that solve it.?
{
"data": [
[
{
"user_id": "654120",
"user_name": "Jhon_Thomsona",
"user_image": null
}
],
[
{
"user_id": "1065040766943114",
"user_name": "Er Ayush_Gemini",
"user_image": "KP8LSHQFwk.png"
}
]
]
}
I want my final array to look like this:
{
"data": [
{
"user_id": "654120",
"user_name": "Jhon_Thomsona",
"user_image": null
},
{
"user_id": "1065040766943114",
"user_name": "Er Ayush_Gemini",
"user_image": "KP8LSHQFwk.png"
}
]
}
You can remove the extra array layer around each user object by mapping reset over the elements of data, then reencoding as JSON.
$data = json_decode($json);
$data->data = array_map('reset', $data->data);
$json = json_encode($data);
Of course, if you are creating this JSON yourself, you should avoid creating this structure to begin with rather than altering it after the fact.
<?php
$foo = json_decode($yourjson);
$data = [];
foreach($foo->data as $array) $data = array_merge($data, $array);
$foo->data = $data;
$yourjson = json_encode($foo);
EDIT Use of array_merge + Oriented object

Categories