Array in Json with Symfony2 - php

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?

Related

PHP Map infinite objects

I have some struggles how to map infinite object in Laravel.
So I have one table Categories that I'm getting in controller like:
$find_parent = Category::where('slug', $slug)->with('childrenRecursive')->first();
childrenRecursive() works fine in that case.
And return of this object would be like (minified):
{
"id": "1cbd459a-ccc0-435b-b9a9-0433e2e9285b",
"parent_id": "f0d29100-d2bc-48c8-89cf-985e0c03b8ac",
"children_recursive": [
{
"id": "30bf23a7-b28c-4s78-b873-1df589eebcb1",
"parent_id": "1cbd459a-ccc0-435b-b9a9-0433e2e9285b",
"children_recursive": [
{
"id": "32312a7-b28c-4s78-b873-1df589eebcb1",
"parent_id": "30bf23a7-b28c-4s78-b873-1df589eebcb1",
}
]
},
{
"id": "32bf23a7-b28c-4s78-b873-1df589eebcb1",
"parent_id": "1cbd459a-ccc0-435b-b9a9-0433e2e9285b",
"children_recursive": []
}
]
}
So from this, I have to get all id's in every object. So I have foreach function in controller that looks like:
$find_parent = Category::where('slug', $slug)->with('childrenRecursive')->first();
$array = [];
foreach($find_parent->childrenRecursive as $l){
array_push($array, $l->id);
if($l->childrenRecursive){
$result = array_merge($array, $this->catTree($l->childrenRecursive));
}
}
return $result;
And catTree would look like:
public function catTree($list){
$tree = [];
foreach($list as $l){
array_push($tree, $l->id);
if($l->childrenRecursive){
array_merge($tree, $this->catTree($l->childrenRecursive));
}
}
return $tree;
}
So this is returning some of the objects, but not everything. What am I doing wrong here?

How to short this code, i'm doing same for each and declare variable

I think my code is ugly for such thing, i'm doing twice foreach.
$peoples;
$container = [];
foreach( $this->media_model->people as $person )
{
$people = Person::whereHas('jobs', function( Builder $query ){
$query->where('job_name', '=', 'Artist');
})->get();
$peoples = $people;
}
$peoples return json
[
{
"person_id": 1,
"first_name": "Suzuki",
"last_name": "Amanda"
},
{
"person_id": 3,
"first_name": "Stephen",
"last_name": null
}
]
i need to do something again with the data to join first name and last name
foreach( $peoples as $person )
{
array_push($container, $person->first_name.' '.$person->last_name);
}
return $container;
In the end the json data will be
[
"Suzuki Amanda",
"Stephen "
]

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

Codeigniter organization chart PHP

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

Remove model name from json array in cakephp

I've set up a custom search action in my cakephp controller
public function search() {
$results = [];
$results['data'] = $this->Content->find('first',
array(
'conditions' => array($this->request->params['pass'][0] . ' like' => "%" . $this->request->params['pass'][1] . "%")), array('contain' => false)
);
if(count($results['data'])>0){
$results['success'] = true;
$this->set(compact('results'));
$this->set('_serialize', array('results'));
}
else{
$results['success'] = false;
}
}
The issue I'm running into is that the rest of my API formats data like this:
{
"success": true,
"data": [
{
"id": "5509be6c-9ef8-42c3-af39-2d492773a233",
"title": "test2",
},
{
"id": "5509be6c-9ef8-42c3-af39-2d492773a233",
"title": "test1"
}
]
}
but what I'm getting from cakephp right now for my search action is this:
{
"results": {
"success": true,
"data": {
"Content": {
"id": "52efcbeb-e984-4a2e-b76f-0cc34056922c",
"title": "Homeasdfasdf",
}
}
}}
How do I get rid of the extra "results" array wrapper so that my data is coming out in the same format?
Use the current() php function. In your controller make
$results = current($results);
before the set() call

Categories