How can I push an object outside a function? - php

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"
}
}
}

Related

Laravel JSON to Array

I have to convert json to arry from the laravel notifications table data field,
This is the the data shown on dd($user->notifications);
This is how the response shows in the postman
I need to show the payload within [] as below
{
"payload": [ {
"title": "PHP Developer Accepted",
"description": "<p>This is a professional IT Job </p>",
"user_id": 54,
"job_id": "01"
}],
"message": "",
"result": true
}
Here's my controller index function
protected function index()
{
$user = DeviceAuthenticator::getUserByAccessToken();
foreach ($user->notifications as $notification) {
$notifications = $notification->data;
}
return response()->apiSuccess($notifications);
}
But before I dump the $notifications before response it shows as an array
dd($notifications);
just wrap in [] your variable which will be like
protected function index()
{
$user = DeviceAuthenticator::getUserByAccessToken();
foreach ($user->notifications as $notification) {
$notifications = $notification->data;
}
return response()->apiSuccess([$notifications]); // wrap in array
}
You may need something like this
protected function index()
{
$user = DeviceAuthenticator::getUserByAccessToken();
$notifications = [];
foreach ($user->notifications as $notification) {
$notifications[] = $notification->data;
}
return response()->apiSuccess($notifications);
}
here notifications is an array
You can try adding this
->toArray();

json style mongodb php query

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 ?

php | dynamic api call

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) ;
}

Array in Json with Symfony2

this is what i want:
[{
"id": 1,
"targetGroup": {
"age": [5],
"gender": [1],
"income": [2]
}
...
,
{
...
}
}]
i want an array in my json return.
Here is my Symfony Action:
public function advertisingPartnersAction() {
$serializer = SerializerBuilder::create()->build();
$em = $this->getDoctrine()->getRepository('MainBundle:Promotion');
$query = $em->createQueryBuilder('qbPromotion')
->select('qbPromotion.id,qbEntry.entTitle,qbIndustry.indTitle,qbPacking.packTitle,qbEntry.edition,qbEntry.tkp')
->join('qbPromotion.entry2', 'qbEntry')
->join('qbEntry.packing', 'qbPacking')
->join('qbEntry.industry', 'qbIndustry')
->getQuery();
$entity = $query->getResult();
if ($entity) {
$jsonEntity = $serializer->serialize($entity, 'json');
} else {
// TODO error
die;
}
return new JsonResponse(json_decode($jsonEntity, true));
}
This works fine and returns:
[
{"id":2,"entTitle":"Titel","indTitle":"Food","packTitle":"Karton","edition":1,"tkp":"38.10"},
{"id":3,"entTitle":"Titel","indTitle":"Food","packTitle":"Karton","edition":1,"tkp":"38.10"},
{"id":1,"entTitle":"Titel 2","indTitle":"Getr\u00e4nke","packTitle":"Flasche","edition":2,"tkp":"38.20"}
]
But i need an array like targetGroup in my json. How can i get it work?

Function is not returning true or false, if it is correct

I am writing a function which checks nested keys if it exists in JSON, but i hav stuck at place when if code is correct then it must return true or false but it is not. it returns null value
php function is
function checkNestedKeysExists($JSONRequest,$keyCheckArray){
$currentKey = current($keyCheckArray);
$JSONRequest = array_change_key_case($JSONRequest, CASE_LOWER);
if(array_key_exists($currentKey,$JSONRequest)){
if($currentKey==end($keyCheckArray)){
return true;
}
else {
array_shift($keyCheckArray);
$this->checkNestedKeysExists($JSONRequest[$currentKey],$keyCheckArray);
//echo "F";
}
}
else{
return false;
}
}
given array is
$keyCheckArray = array('data','device_info','deviceid');
and $JSONRequest is
{
"timestamp": "2014-01-01 11:11:11",
"data": {
"requestid": "bcpcvssi1",
"device_info": {
"os": "Android",
"deviceId": "123123",
"userProfile": {
"email": [
"abc#gmail.com"
],
"gender": "Male",
"age": "19",
"interest": [
"Apple",
"Banana"
]
}
}
}
}
Modify the line of your code where you make recursive call like following
return $this->checkNestedKeysExists($JSONRequest[$currentKey],$keyCheckArray);
So it will return the result of the call
pass $JSONRequest in
json_decode($JSONRequest, true);
EDIT: Sorry I got it wrong in first time.
Use array[0] instead of current() if you are shifting elements, maybe it is making a problem. And of course, do the var_dump() to check values.
$currentkey = 'data' and end($keyCheckArray) = 'deviceid'. That will never return true, hence you have no return values specified and it will return null.
two advices:
give the function with every possible way to end the function a valid return value.
create a variable for every fixed outcome like end($keyCheckArray).
If have tested your function (and edited it for testing purposes):
function checkNestedKeysExists($JSONRequest,$keyCheckArray){
$currentKey = current($keyCheckArray);
$JSONRequest = array_change_key_case($JSONRequest, CASE_LOWER);
$endValue = end($keyCheckArray);
if(array_key_exists($currentKey,$JSONRequest)){
print 'currentKey = '.$currentKey.", end = ".$endValue."<br>\n";
if($currentKey== $endValue){
return 'correct';
}else {
array_shift($keyCheckArray);
$p = checkNestedKeysExists($JSONRequest[$currentKey],$keyCheckArray);
print "p = ".$p."<br>\n";
//echo "F";
return $currentKey;
}
}
else{
return false;
}
}
The output is like this:
correct
device_info
data
I suggest you change your function into a while loop. Once you have found the requested result, return true.

Categories