merge Array of objects into array with unique object - php

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

Related

Unset null values in array of DOM elements

I am iterating trough array in php and I got result like:
It's a an array with DOM elements within a DOM Crawler library.
{
"data": [
{
"content": null,
"property": null
},
{
"content": "Build your communication strategy and unleash the effectiveness and efficiency of your storytelling",
"property": null
}
}
...
In my code:
$crawler = new Crawler(file_get_contents($url));
$items =$crawler->filter('meta');
$metaData = [];
foreach ($items as $item) {
$itemCrawler = new Crawler($item);
$metaData[] = [
'content' => $itemCrawler->eq(0)->attr('content'),
'property' => $itemCrawler->eq(0)->attr('property')
];
}
What I try to accomplish is to get rid of rows where both fields are NULL like first one (if there is one of the fileds, like second one than skip).
Tried with array_filter() but with no success.
return array_filter($metaData, 'strlen');
Not sure why the first answer wouldn't be accepted. It would be just a bit of tweaks to make it work.
In your loop
$itemCrawler = new Crawler($item);
$content = $itemCrawler->eq(0)->attr('content');
$property = $itemCrawler->eq(0)->attr('property');
if(!is_null($content) || !is_null($property)) {
$metaData[] = compact('content', 'property');
}
Or if you insist on using array_filter after getting the $metaData array
$filteredMetaData = array_filter($metaData, function($item) {
return !is_null($item['content']) || !is_null($item['property']);
});
Actually, array_filter() works for empty elements.
Even if the element values are blank, if the keys are there, the blank values will not be removed.
In the code:
$item Has two keys
So, add explicit conditions to check for blank elements and please modify the code like:
$data = [];
$items =$service->get('allData');
foreach ($items as $item) {
if (! empty($item['content']) && ! empty($item['property'])) {
$data[] = [
'content' => $item['content'],
'property' => $item['property]
];
}
}

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

Laravel show data from database and convert to json

i'm trying show data from database on laravel, but don't show anything in view blade. Every group hasMany lapangan(eng: court) data
$groups_resource = Groups::all();
$groups = [];
foreach($groups_resource as $group)
{
$g = new Groups();
$g->id_group = "Group_".$group['id_group'];
$g->name = $group['nama'];
$g->expanded = true;
$g->eventHeight = 25;
$g->children = array();
$groups[] = $g;
$lapangan_resource = Lapangan::with('groups')->orderBy('nama')->get();
foreach($lapangan_resource as $lapangan)
{
$l = new Lapangan();
$l->id_lapangan = $lapangan['id_lapangan'];
$l->name = $lapangan['nama_lapangan'];
$g->children[] = $l;
}
}
return json_encode($groups);
output
[{"id_group":"Group_1","name":"Lapangan Badminton","expanded":true,"eventHeight":25,"children":[]},{"id_group":"Group_2","name":"Lapangan Tenis","expanded":true,"eventHeight":25,"children":[]}]
There is no children output for every id_group
.what i want
{"id":"group_1","name":"Indoor","expanded":true,"eventHeight":25,"children":[
{"id":"1","name":"Court 1"},
{"id":"2","name":"Court 2"},
{"id":"3","name":"Court 3"},
{"id":"4","name":"Court 4"}]},
{"id":"group_2","name":"Outdoor","expanded":true,"eventHeight":25,"children":[
{"id":"11","name":"Court 5"},
{"id":"12","name":"Court 6"},
{"id":"13","name":"Court 7"},
{"id":"14","name":"Court 8"}]}
]
Any idea?
If you want to return a response in JSON format than you can use json() method as:
return response()->json($datagrup);
OR
To convert a model to JSON, you should use the toJson method. Like toArray, the toJson method is recursive, so all attributes and relations will be converted to JSON:
$user = App\User::find(1);
return $user->toJson();
Even though, you code seems to really fixed... I still feel the below code should work for you :)
I am not sure what exactly you mean by $datagroup[] = $dataresource? Do you want to add datagroup to dataresource or dataresource to datagroup... Your code shows something and the output desired is something else.
$datagroup = array_map(function($groups) use ($scheduler_resources) {
return [
'id' => $group['id_group'],
'name' => $group['nama'],
'expanded' => true,
'children' => $scheduler_resources->map(function($resource) {
return [
'id' => $resource->id_lapangan,
'name' => $resource->nama_lapangan,
];
}),
'eventHeight' => 25
];
}, $scheduler_groups);
echo json_encode($datagroup);
// or
// return response()->json($datagroup);
Note :- Please ensure $scheduler_resources is different for each $datagroup

decode multiple json object php

I have this jsone that I need to convert in three different objects.
in some php. I know that i have to use json_decode but I only decode the first object , the others 2 object don't.
{
"recorrido":[
{
"lon":"-60.67216873168769",
"lat":"-32.9230105876913",
"date":"13/10/24-12:22:32",
"globaltime":"00:09",
"globalkm":0.0,
"speed":2.11,
"altitude":-32.9230105876913,
"groupId3":0,
"id":1,
"color":0,
"auxInt":0,
"groupId2":0,
"provider":1,
"groupId1":0,
"workoutid":1
},
{
"lon":"-60.67216873168769",
"lat":"-32.9230105876913",
"date":"13/10/24-12:22:35",
"globaltime":"00:12",
"globalkm":0.0,
"speed":2.11,
"altitude":-32.9230105876913,
"groupId3":0,
"id":2,
"color":0,
"auxInt":0,
"groupId2":0,
"provider":1,
"groupId1":0,
"workoutid":1
}
],
"user":{
"asunto":"",
"userId":1
},
"Itemout":{
"uploaded":"false",
"isSelected":false,
"id":1,
}
}
what do you sugest? the script must be in php. the object "recorrido" is a multiple array object.
wthout testing it, try somrting like this:
$tempArray = (array)$recorrido; // or how you cal your json object
foreach ($tempArray as $tempJson)
{
$myArray = json_decode($tempJson);
print_r($myArray);
}
You can use hardcode method if you have static json structure:
Show below
$result = json_decode($json);
$recorrido = $result->recorrido;
// And so on
In another way there is a workaround with arrays.
list($arr1, $arr2, $arr3) = json_decode($json, true);
This solution will make you three arrays of data from json.

Categories