Changing how returned json response looks - php

I'm trying to return a Json array and it works, but the other application I'm using the API for can't accept the format that the json is printed it (the way it looks, that is).
Example:
{
"123": [
{
"id": 1
}
]
}
But I need it to be:
"123":
{
"id": 1
}
Using this code:
$param = 123;
$array = User::all();
return \Response::json([$param => $array], 200, array(), JSON_PRETTY_PRINT);
Is this possible to do somehow?

I guess what you want is:
{
"123":
{
"id": 1
}
}
If you are sure you want to send just a single user, and not an array of users you can do:
$param = 123;
$user = User::first(); //Or any other Eloquent query, which gets the exact user you want
return response()->json([$param => $user]);

Related

How to show array in Json with Fractal?

I want to save REST API data with array to database, its work, all value save to the table, but i still get error when i want to view the result in json.
Here is my error
"message": "Argument 1 passed to App\\Transformers\\NewLoanOfferTransformer::transform() must be an instance of App\\Model\\AntiAttrition, array given, called in /home/insko23/testing.insko.my/vendor/league/fractal/src/Scope.php on line 338",
My Controller
public function new_loan_offer(Request $request, AntiAttrition $antiattrition)
{
$new = array_map(null, $request->mo_id, $request->id_clrt,$request->TaskID,$request->ACID,$request->CustIDNo);
foreach($new as $new) {
$request = new AntiAttrition;
$request->mo_id = $new[0];
$request->id_clrt = $new[1];
$request->TaskID = $new[2];
$request->ACID = $new[3];
$request->CustIDNo = $new[4];
$request->save();
}
$response = fractal()
->item($new)
->transformWith(new NewLoanOfferTransformer)
->toArray();
return response()->json($response,201);
}
My App\Transformer
<?php
namespace App\Transformers;
use App\Model\AntiAttrition;
use App\Model\SettlementInfo;
use League\Fractal\TransformerAbstract;
class NewLoanOfferTransformer extends TransformerAbstract
{
public function transform (AntiAttrition $antiattrition)
{
return[
'id' => $antiattrition->id,
'mo_id'=> $antiattrition->mo_id,
'assign_by'=> $antiattrition->assigned_by,
'id_clrt' => $antiattrition->id_clrt,
'TaskID'=> $antiattrition->TaskID,
'ACID'=> $antiattrition->ACID,
'CustIDNo'=> $antiattrition->CustIDNo
];
}
}
I want to show the result in json, like below
{
"data": [
{
"mo_id": "123",
"id_clrt": "10000000049",
"ACID": "123",
.....
},
{
"mo_id": "1234",
"id_clrt": "10000000045",
"ACID": "1235",
.....
},
{
"mo_id": "124",
"id_clrt": "10000000044",
"ACID": "1245",
.....
},
],
}
Please help me to solve this problem
In the foreach loop, avoid using same name for array and elements of the array you are iterating over, you can rename foreach($new as $new) to foreach($newArray as $new), or something meaningful with your code logic. Also rather than using $new[0] use $new['mo_id'] for referring to the key of the array

php: combining variable values of the same type?

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

JSON Structure changed, breaks methods

Currently, I have below JSON stored in my database:
{
"1": [
{
"row": "My name is Trevor"
}
],
"2": [
{
"row": "Hey there! Some other text."
}
],
"3": [
{
"row": "And more."
}
]
}
Now, the third party API that I am using have changed their output format to:
[
{
"0":"My name is Trevor"
},
{
"0":"Hey there! Some other text."
},
{
"0":"And more."
}
]
I have a PHP function that reads the array-like colums and transforms each column/row. I can call it like:
public function apply(array $table) : array
{
return $this->applyRule($table);
}
Which calls this:
public function applyRule(array $table): array
{
$out = [];
foreach ($table as $col => $rows) {
$out[$col] = array_map([$this, 'rule'], $rows);
}
return $out;
}
Which ultimately calls the parsing rule, like so:
public function rule($content) : array
{
return preg_replace($this->pattern, $this->replacement, $content);
}
However, running above gives me below error:
regexTextReplace::rule() must be of the type array, string returned
I suspect that due to the change in the JSON structure, my parsing functions no longer work.
I am not sure what needs to be changed - can someone assist me?
Edit:
So looking at the answer below, adding [$rows] instead of $rows fixes the error, but ultimately creates a nested array it seems.
If I do a die-dump like:
dd($rows);
It actually does return an array:
array:3 [▼
0 => "My name is Trevor"
1 => ""
2 => ""
]
So why is it seen as a string?
You can send $rows as an array to the rule() function, just wrapping it in []:
array_map([$this, 'rule'], [$rows]);
Then the function will receive an array, not a string.
Otherwise, you can refactor your code and use a string instead, but I can't see much advantage.

How to get all records in if conditions using Laravel

I have two request parameters in array:
{
"users": [1,2,3],
"groups": [1,2]
}
I want to get records of users against id 1,2,4 and groups against id 1,2 I can fetch records of users but I am unable to fetch records of groups.
Here is my code:
public function isGroupUser(Request $request)
{
$usersDetail = $request->input('users', []);
$groupsDetails = $request->input('groups', []);
if($usersDetail)
{
$users = DB::table('users')
->join('user_basic_info','users.id','=','user_basic_info.user_id')
->select('users.id','user_basic_info.first_name')
->whereIn('users.id',$usersDetail)->get();
$resultArray = ['users' => $users];
return \Illuminate\Support\Facades\Response::json($resultArray, 200);
}
elseif ($groupsDetails)
{
$groups = DB::table('group')
->select('group.id','group.name')
->whereIn('group.id',$groupsDetails)->get();
$resultArray = ['groups' => $groups];
return \Illuminate\Support\Facades\Response::json($resultArray, 200);
}
}
I can get the records of users but not getting groups. Where am I wrong?
Currently my JSON response:
{
"users": [
{
"id": 1,
"first_name": "Admin"
},
{
"id": 2,
"first_name": "Admin"
},
{
"id": 3,
"first_name": "Admin"
}
]
}
But not getting the groups.
You got some problems
You are replacing resultArray when you are trying to assign groups to it,
You are writing elseif condition which suggest, only one of two condition will always satisfy
Change these two lines
$resultArray['users'] = $users; // here result array will have key users
$resultArray['groups'] = $groups; // here result array will have key groups
elseif ($groupsDetails) replace this with if($groupsDetails)
In above case, its pushing data into array. In your case its replacing array.
It should work.
change your code like below,
in your code only one part (either if or elseif) works
$usersDetail = $request->input('users', []);
$groupsDetails = $request->input('groups', []);
$resultArray = []; // an empty array to store your results
if($usersDetail)
{
$users = DB::table('users')
->join('user_basic_info','users.id','=','user_basic_info.user_id')
->select('users.id','user_basic_info.first_name')
->whereIn('users.id',$usersDetail)->get();
$resultArray['users'] = $users;
}
if ($groupsDetails)
{
$groups = DB::table('group')
->select('group.id','group.name')
->whereIn('group.id',$groupsDetails)->get();
$resultArray['groups'] = $groups;
}
return \Illuminate\Support\Facades\Response::json($resultArray, 200);
just remove first return. because if in request have user then when got to return and then get out from if anad not get to second return.
edited: #Shobi answered well

merge Array of objects into array with unique object

I have a array of various object, but I need turn this objects into unique object. Below I share my code.
$result = [];
$idiomas = Idioma::all()->toArray();
foreach ($idiomas as $lang) {
$result[] = [
$lang['palavra_chave'] => $lang[$id]
];
}
return response()->json($result);
reponse
[
{ "INICIAL": "Inicial"},{ "RELATORIOS": "Relatórios"},{ "FUNCIONARIO": "Funcionário"},{ "DATA": "Data"},{ "ANEXAR_IMAGEM": "Anexar imagem"},{ "DISCIPLINA": "Disciplina"}
]
But I need transform this objects into one, like this
[
{
"INICIAL": "Inicial",
"RELATORIOS": "Relatórios",
"FUNCIONARIO": "Funcionário",
"DATA": "Data",
"ANEXAR_IMAGEM": "Anexar imagem",
"DISCIPLINA": "Disciplina"
}
]
anyone can help me?
$idiomas = Idioma::all()->toArray();
if (count($idiomas)) {
//$result = new stdClass; # wouldn't work without base namespace
$result = new \stdClass;
foreach ($idiomas as $lang) {
$result->{$lang['palavra_chave']} = $lang[$id];
}
return response()->json([$result]);
}
// otherwise
Edit: #Tpojka's answer definitely looks more appropriate. Use the following one only if you can't change the way you retrieve data initially (I'm not familiar enough with Laravel).
The following should work:
// Take your initial JSON
$input = <<<JSON
[
{ "INICIAL": "Inicial"},{ "RELATORIOS": "Relatórios"},{ "FUNCIONARIO": "Funcionário"},{ "DATA": "Data"},{ "ANEXAR_IMAGEM": "Anexar imagem"},{ "DISCIPLINA": "Disciplina"}
]
JSON;
// Transform it into a PHP array
$input_as_array = json_decode($input);
// Reduce it into an associative array
$associative_array = array_reduce($input_as_array, function($associative_array, $item) {
return $associative_array += (array)$item;
}, []);
// Encode it back into JSON, as an array
$result = json_encode([$associative_array], JSON_PRETTY_PRINT);

Categories