How to show array in Json with Fractal? - php

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

Related

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.

PHP - Perform parsing rules on nested array

So I have a nested array, that mimics a table layout (columns and rows):
{
"1": [
{
"row": "My name is Trevor\n"
},
{
"row": "Can you see me?\n"
},
{
"row": "\f"
}
],
"2": [
{
"row": Hey there! Some other text.\n"
},
{
"row": "What is up?\n"
},
{
"row": "\f"
}
],
"3": [
{
"row": "Some text on the third column. First row."
},
{
"row": "\f"
}
]
}
So "1", "2", "3" are the columns and then under each column, there can be any number of rows.
Now I am trying to do, so my users can perform various parsing rules on either:
All columns and all rows.
Specific columns and all rows.
Whenever a column / row has been parsed, it should be returned to the "original array".
For this, I have created a class that will apply the different parsing rules I have in specified. Getting the parsing rule works fine. I am currently stuck in the actual text transformation/parsing aspect.
Consider I have a parsing rule called "regexTextReplace", that looks like this:
class regexTextReplace
{
private $pattern;
private $replacement;
public function __construct(array $arguments)
{
$this->pattern = $arguments['pattern'];
$this->replacement = $arguments['replacement'];
}
public function apply(array $table, $column = false): array
{
$table = $column ? $table[$column] : $table;
return array_map('self::regex_replace', $table);
}
public function regex_replace(array $table)
{
return preg_replace($this->pattern, $this->replacement, $table);
}
}
This is how I'm using it:
$options = [
'pattern' => '/Trevor/i',
'replacement' => 'Oliver',
];
$engine = new regexTextReplace($options);
$columns = $engine->apply($document->content, 1); //"1" is the specific column.
$columns returns:
[
{
"row": "My name is Oliver\n"
},
{
"row": "Can you see my?\n"
},
{
"row": "\f"
}
]
Two problems here:
It successfully apply the parsing rule (Trever is replaced with Oliver). But it only returns the first column, but I want the entire original array to be transformed.
If I remove the 1 from the apply() method, I get below error:
Array to string conversion
on below line:
return preg_replace($this->pattern, $this->replacement, $table);
Can anyone guide me in the right direction, so I can perform my parsing rule on any column or on all columns, and return the transformed data back to my original array?
I would rewrite the apply function to loop over the entire table, processing each column if the column argument is not set, or if it matches the current table column:
public function apply(array $table, $column = false): array
{
$out = array();
foreach ($table as $col => $rows) {
if ($column === false || $col == $column) {
$out[$col] = array_map('self::regex_replace', $rows);
}
else {
$out[$col] = $rows;
}
}
return $out;
}
Demo on 3v4l.org
You could rewrite your apply method to this:
public function apply(array $table, $columns = false): array
{
$columns = $columns === false ? array_keys($table) : (array)$columns;
return array_map(function ($column) use ($table, $columns) {
return in_array($column, $columns) ? array_map('self::regex_replace', $table[$column]) : $table[$column];
}, array_keys($table));
}
You can pass either a single column, or an array of columns, or nothing (false) to specify the columns you want adjusted.
Demo: https://3v4l.org/Kn4FY
Just loop it and do the regex on all subarrays:
$content = json_decode($json, true);
$options = [
'pattern' => '/Trevor/i',
'replacement' => 'Oliver',
];
$engine = new regexTextReplace($options);
foreach($content as $key => $v){
$columns[$key] = $engine->apply($content, $key);
}
var_dump($columns);
Working demo:
https://3v4l.org/Pk2rC
The benefit of looping in the "PHP" side instead of in the class is that you can still apply the regex to only one or two of the subarrays.
If you loop in the class then you need to pass more arguments to restrict the looping or do some type of array slicing.

PHP using json_encode, must output the specific data

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).

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