I need to create mongodb query using json format like I do in studio 3T.
For example i exceute this "where" in studio 3t and it works fine
{ $and: [ { "message": { $not: /.*status=sent.*/i } }, { "message": { $not:
/.*status=bounce.*/i } }, { "message": { $not: /.*message-id.*/i } } ] }
But I don't know how to use it in php.
I can create queris this way:
public function connect(...)
{
...
self::$connect = new MongoDB\Driver\Manager('mongodb://'.$data);
}
public function query($table, $filter = array(), $options = array())
{
if(!self::$connect)
{
self::$connect = $this->connect();
}
$query = new \MongoDB\Driver\Query(
$filter, // query (empty: select all)
$options // options, example: ['limit' => 40 ]
);
return self::$connect->executeQuery($this->dbName.'.'.$table, $query);
}
$result = $mongo->query('messages', $filter, array('limit' => 1000));
How to make it using json-style ?
Related
I need to write an API that have all the table column but with the option of skipping the nullable field/column.
somehow the array return empty, can you figured out what happen?
store function ==>
public function store(Request $request)
{
$dataTable = [];
function checkifexist($column,$request_name,$request,$dataTable){
if($request->has($request_name)){
addData($column,$request_name,$dataTable);
}
}
function addData($column,$request_name,$request,$dataTable){
// $dataTable[$column] = $request[$request_name];
array_push($dataTable,array($column => $request[$request_name]));
}
try {
addData("example_field","example_field",$request,$dataTable); //required
checkifexist("example_number_two","example_number_two",$request,$dataTable);
//check if the request have this option
item::create($dataTable);
$data["success"] = true;
$data["code"] = 200;
$data["message"] = "success";
$data["data"] = ["this is the data you are inputing"=>$dataTable];
} catch (\Throwable $th) {
$data["data"] = [];
$data["success"] = false;
$data["code"] = 500;
$data["message"] = $th->getMessage();
}
return $data;
}
postman request ==>
method = "post";
body:{
example_field:"value"
}
result of postman ==>
{
"success": true,
"code": 200,
"message": "success",
"data": {
"this is the data you are inputing": []
}
}
so this one work.
i return the data in the function and then replace the array with the new value
Credit to: EL_VANJA
$dataTable = [];
function addData($column,$request_name,$request,$dataTable){
$dataTable[$column] = $request[$request_name];
return $dataTable;
}
function checkifexist($column,$request_name,$request,$dataTable){
if($request->has($request_name)){
$newData = addData($column,$request_name,$request,$dataTable);
return $newData;
}
}
$dataTable = addData("item_id","item_id",$request,$dataTable);
$dataTable = checkifexist("name","name",$request,$dataTable);
postman result ==>
{
"success": true,
"code": 200,
"message": "success",
"data": {
"this is the data you are inputing": {
"ExampleField": "1",
"ExampleFiledTwo": "sdsad"
}
}
}
Whats the best way to output a json like an organization chart? Seems my loop is not good. Can't really get whats the empUnd for every employees. How to make a good loop for this type of chart like get every empUnd over and over until its empty
Create endpoint that shows the organization structure.
/test/chart
Response Format:
{
"empNo: "123",
"name": "Jennifer Sy",
"jobDesc": "CEO",
"empUnd: [
{
"empNo": "456",
"name": "Mike Tolomia",
"jobDesc": "VP",
"empUnd": [{}]
}
]
}
Here's my controller:
public function chart() {
$employeeDetails = $this->api_model->fetch_employees();
foreach ($employeeDetails as $employeeDetail) {
$test = $this->api_model->checkEmployeeUnder($employeeDetail['employeeNumber']);
$result[] = [
'empNo' => $employeeDetail['employeeNumber'],
'name' => $employeeDetail['firstName'],
'empUnd' => $test
];
}
return $this->output->set_content_type('application/json')->set_output(json_encode($result));
}
My Model:
public function fetch_employees()
{
$qry = $this->db->get('employees');
$result = $qry->result_array();
return $result;
}
public function checkEmployeeUnder($reportsTo)
{
$this->db->select('empNo, CONCAT(firstName, '.' , " ", lastName) AS name');
$this->db->from('employees');
$this->db->where('reportsTo', $reportsTo);
$qry = $this->db->get();
$result = $qry->result_array();
return $result;
}
I am new to PHP coming over from Javascript. I have 2 PHP methods. I'd like to combine them into one endpoint call. Can I push them into the same Array so they can come back in one call with one payload?
public function incompleteOrders()
{
$orders = request()->user()->incompleteOrders();
$data = $orders->toArray();
return response($data, 200);
}
public function finishedOrders()
{
$orders = request()->user()->finishedOrders();
$data = $orders->toArray();
return response($data, 200);
}
You can set multiple keys on the resulting json object, for example:
public function orders()
{
$data = [
'incomplete' => request()->user()->incompleteOrders(),
'finished' => request()->user()-> finishedOrders(),
];
return response($data, 200);
}
The json will look something like this:
{
"finished": [
{
"id": 1
}
],
"incomplete": [
{
"id": 2
},
{
"id": 3
}
]
}
Hello you can fetch the two array and combine them in another array like what we have bellow
public function userOrders()
{
$finishedOrders = request()->user()->finishedOrders();
$incompleteOrders = request()->user()->incompleteOrders();
$data = ["finishedOrders" => $finishedOrders->toArray(), "incompleteOrders" => $incompleteOrders->toArray()];
return response($data, 200);
}
Or you can also use array_merge a php function to merge the two array in one
I'm currently stuck at this scenario, now the other developer wants to output the API structure as seen on attached image.
json_required_format
But I tried as far as I can but I only got these result:
"all_projects": {
"TEST TOWNHOMES": {
"unit_types": [
{
"unit": "TOWNHOUSE 44.00"
}
]
},
"TEST HOMES": {
"unit_types": [
{
"unit": "DUPLEX WITH OUT GARAGE 44.50"
}
]
},
"TEST HOMES II": {
"unit_types": [
{
"unit": "DUPLEX WITH OUT GARAGE 44.50"
}
]
},
"TEST VILLAGE": {
"unit_types": [
{
"unit": "TOWNHOUSE 44.00"
},
{
"unit": "DUPLEX WITHOUT GARAGE 52.30"
}
]
}
I am using MVC framework,
This is my model looks like:
public function all_south_projects()
{
$this->db->distinct();
return $this->db->select('Project as project_name')->from('lots')
->where('available','YES')
->get()->result();
}
public function get_unit_types($projName)
{
$this->db->distinct();
return $this->db->select('UnitType as unit')->from('lots')
->where('Project',$projName)
->where('Available','YES')
->get()->result();
}
And then my controller is:
$resp = $this->MyModel->all_south_projects();
$test_array = array();
foreach ($resp as $value) {
$units = $this->MyModel->get_unit_types($value->project_name);
$allunits = array("unit_types"=>$units);
$allunits = (object) $allunits;
$test_array[$value->project_name] = $allunits;
}
//var_dump($test_array);
$stat = 200;
$message = 'Successfully fetched.';
if(empty($test_array)){
$empty=json_decode('{}');
json_output2($stat,'all_projects',$message,$empty);
}else{
json_output2($stat,'all_projects',$message,$test_array);
}
json_output2 is on my helper to customize json format:
Here is my code:
function json_output2($statusHeader,$responseName,$message,$response)
{
$ci =& get_instance();
$ci->output->set_content_type('application/json');
$ci->output->set_status_header($statusHeader);
$ci->output->set_output(json_encode(array('status' =>
$statusHeader,'message' => $message,$responseName =>$response)));
}
NOTE: Scenario is:
The API must give all the projects having available units,
if the project is available, then it needs to get its corresponding available units to view. I know I can make another API call but this time, we need to improve the UX.
Can someone enlighten me to get through this? Thank you!
Change this part :
foreach ($resp as $value) {
$units = $this->MyModel->get_unit_types($value->project_name);
$allunits = array("unit_types"=>$units);
$allunits = (object) $allunits;
$test_array[$value->project_name] = $allunits;
}
To :
foreach ($resp as $value) {
$units = $this->MyModel->get_unit_types($value->project_name);
$test_array[] = [
"project_name" => $value->project_name,
"unit_types" => $units
];
}
You don't have to cast your associative array to object like you did there : $allunits = (object) $allunits; because an associative array will always be serialized as a JSON object (associative arrays do not exist in JSON).
I am trying to create a dynamic endpoint for a API I am creating in order to include some data but only if it is required so I can use it in multiple places.
The idea is to have api.domain.com/vehicle to bring back basic vehicle information but if I did api.domain.com/vehicle?with=owners,history then the idea is to have a function which maps the owners and history to a class which will return data but only if it is required.
This is what I currently have.
public static function vehicle()
{
$with = isset($_GET['with']) ? $_GET['with'] : null;
$properties = explode(',', $with);
$result = ['vehicle' => Vehicle::data($id)];
foreach ($properties as $property) {
array_push($result, static::getPropertyResponse($property));
}
echo json_encode($result);
}
Which will then call this function.
protected static function getPropertyResponse($property)
{
$propertyMap = [
'owners' => Vehicle::owner($id),
'history' => Vehicle::history($id)
];
if (array_key_exists($property, $propertyMap)) {
return $propertyMap[$property];
}
return null;
}
However, the response I'm getting is being nested within a index, which I don't want it to be. The format I want is...
{
"vehicle": {
"make": "vehicle make"
},
"owners": {
"name": "owner name"
},
"history": {
"year": "26/01/2018"
}
}
But the format I am getting is this...
{
"vehicle": {
"make": "vehicle make"
},
"0": {
"owners": {
"name": "owner name"
}
},
"1": {
"history": {
"year": "26/01/2018"
}
}
}
How would I do this so it doesn't return with the index?
Vehicle::history($id) seems to return ['history'=>['year' => '26/01/2018']], ...etc.
foreach ($properties as $property) {
$out = static::getPropertyResponse($property) ;
$result[$property] = $out[$property] ;
}
Or your methods should returns something like ['year' => '26/01/2018'] and use :
foreach ($properties as $property) {
$result[$property] = static::getPropertyResponse($property) ;
}