Laravel sort by keys - arrays

I make an array with collections with code:
$hours = Voucher::where('created_at','>=', Carbon::now()->startOfMonth())->get()->groupBy(function($item)
{
return $item->created_at->format('H');
});
dd($hours);
so I get data like this:
SO keys are hours (00-23).
How I can arrange it starting by 00, 01, 02, 03 ... ...

https://laravel.com/docs/5.6/collections#method-sortkeys
$collection = collect([
'id' => 22345,
'first' => 'John',
'last' => 'Doe',
]);
$sorted = $collection->sortKeys();
Update for 5.1
Since you're using Laravel 5.1 and there is no sortKeys method, you can sort the collection before you group it which should result in the keys being in the correct order.
$collection->sort(function($a, $b) {
return strcmp($a->created_at->format('H'), $b->created_at->format('H'));
})->groupBy(function($item) {
return $item->created_at->format('H');
});

Try this code.
$hours = Voucher::where('created_at','>=', Carbon::now()->startOfMonth())->get()->sortBy(function($item)
{
return $item->created_at->format('H');
});
$hours = $hours->groupBy(function($item)
{
return $item->created_at->format('H');
});
dd($hours);

Related

ANGULAR Components array key in result get value by id

this.crudService.get('user.php?mode=test')
.subscribe((data:any) => {
{ for (var key in data) { this[key] = data[key]; } };
}
);
This use to work on angular 7 now on angular 13 i get this error (look image)
In template i was using the values for example in json string was and array and i had users, in template was {{users}} , {{posts}} etc.. now the this[key] give error , please help me out its very important can't find solution
i'll show an example code, and then applied to your code:
Example
// creating global variables to receive the values
users: any = null;
posts: any = null;
// simulating the data you will receive
data: any[] = [
{users: ['user1', 'user2', 'user3']},
{posts: ['post1', 'post2', 'post3']}
];
getCrudService() {
// access each object of the array
this.data.forEach(obj => {
// getting keys name and doing something with it
Object.keys(obj).forEach(key => {
// accessing global variable and setting array value by key name
this[String(key)] = obj[String(key)]
})
})
}
Apllied to your code
this.crudService.get('user.php?mode=test').subscribe((data:any) => {
data.forEach(obj => {
Object.keys(obj).forEach(key => {
this[String(key)] = obj[String(key)]
});
});
});
I hope it helped you, if you need help, just reply me.

Iterating through a JSON array and returning a subset of elements

I'm new to JS and trying to figure out how to iterate through a json array and return only a subset of elements. Specifically I would like to know how to return only the 'first_name' and 'last_name' from the Mock data in the attached code snippet. It seems like it should be straightforward but I'm scratching my head.
let people = [{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"tkohnert0#wisc.edu","country":"Indonesia"},
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"rmckleod1#gizmodo.com","country":"Sweden"},
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"lfoister2#epa.gov","country":"Nicaragua"}]
people.forEach(person => {
for (let key in person) {
console.log(`${key} => ${person[key]}`);
}
Use the element names
people.forEach(person => {
console.log(JSON.stringify(person) + "\n");
console.log(person["first_name"], person["last_name"], "\n");
});
Produces this output:
{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"tkohnert0#wisc.edu","country":"Indonesia"}
Talbert Kohnert
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"rmckleod1#gizmodo.com","country":"Sweden"}
Ruthie McKleod
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"lfoister2#epa.gov","country":"Nicaragua"}
Lenore Foister
You can try Object destructuring assignment of ES6 to achieve the requirement.
Working Demo :
let people = [{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"tkohnert0#wisc.edu","country":"Indonesia"},
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"rmckleod1#gizmodo.com","country":"Sweden"},
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"lfoister2#epa.gov","country":"Nicaragua"}];
let res = people.map(({first_name, last_name}) => first_name + ' ' + last_name);
console.log(res);
There are numerous way of achieving this output. One of most frequently used method is using map() of es6.
let people = [{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"tkohnert0#wisc.edu","country":"Indonesia"},
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"rmckleod1#gizmodo.com","country":"Sweden"},
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"lfoister2#epa.gov","country":"Nicaragua"}]
//by map method
people.map((person,index)=>{
console.log(`${person.first_name} ${person.last_name}`)
})
// by forEach
people.forEach(person => {
console.log(`${person.first_name} ${person.last_name}`)
}
you can achieve this by using the map function.
map lets you iterate over each item in the array and return a new value for each iteration while returning a new array, so for your case:
let people = [
{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"tkohnert0#wisc.edu","country":"Indonesia"},
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"rmckleod1#gizmodo.com","country":"Sweden"},
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"lfoister2#epa.gov","country":"Nicaragua"}
]
const newArray = people.map((person) => {
return {
first_name: person.first_name,
last_name: person.last_name
}
})
console.log(newArray)
here you get a new array with just the properties you need.

Hos to get a json nested in laravel

I'm use laravel 7
I want a json like this:
"declaracion": {
"situacionPatrimonial": {
"datosGenerales": {
"nombre": "Pedro",
"primerApellido": "Perez",
"segundoApellido": "García",
"curp": "BADD110313HCMLNS09",
}
}
}
This branch works fine, I have no problem to generate it:
"datosGenerales": {
"nombre": "Pedro",
"primerApellido": "Perez",
"segundoApellido": "García",
"curp": "BADD110313HCMLNS09",
}
My code looks like this
$records = [];
foreach ($declaraciones as $declaracion) {
$record = [];
$record['datosGenerales']=$declaracion->datosGeneralesApi($id,$declaracion->servidor_publico);
$records[] = $record;
}
return $records;
datosGeneralesApi it's a trait
But i don´t know how add above o nest this branches
"declaracion": {
"situacionPatrimonial": {
Please any ideas? Thanks in advance
I may not quite understand your question, but I hope I can help
$records = [];
foreach ($declaraciones as $declaracion) {
// Here we create the nested items:
$record = [
"declaracion" => [
"situacionPatrimonial" => []
]
];
// Now access it
$record["declaracion"]["situacionPatrimonial"]['datosGenerales'] = $declaracion->datosGeneralesApi($id,$declaracion->servidor_publico);
$records[] = $record;
}
return $records;
You could also consider doing this a couple of other ways, without accessing with keys:
$record = [
"declaracion" => [
"situacionPatrimonial" => $declaracion->datosGeneralesApi($id,$declaracion->servidor_publico);
]
];
$records[] = $record;
Or create it in a much more structured way:
// Create the last element:
$situacionPatrimonial = $declaracion->datosGeneralesApi($id,$declaracion->servidor_publico);
// Wrap that in the next element:
$declaration = ["situacionPatrimonial" => $situacionPatrimonial];
// Now create your record, with the wrapped element:
$record = ["declaracion" => $declaration];
$records[] = $record;
I hope this explains what you don't understand about nesting even if it doesn't directly answer your question.
I would recommend using Eloquent API Resources. You can easily nest different resources in each other and structure them in any way you want.

AngularJs - json_encode returning nothing in certain cases

I'm using $http.get to get some information from the server. First the controller calls the BackendServices, and in the service i call $http.get:
Controller:
app.controller('courseController', ['$scope', 'BackendServices', function ($scope, BackendServices) {
BackendServices.lookForCourses().then(
function (response) {
console.log(response);
},
function (response) {
}
);
$scope.addCourse = function (courseName) {
console.log(courseName);
};
}]);
Service:
app.service('BackendServices', function ($http) {
var backendServices = {};
backendServices.lookForCourses = function () {
return $http.get('app/backend/lookForCourses');
}
return backendServices;
});
The PHP files works under cakePHP framework.
lookForCourses:
public function lookForCourses () {
$this->autoRender = false;
$cursosFind = $this->Curso->find('all', array('fields' => array('nombreCurso')));
$cursos = array();
foreach($cursosFind as $index => $curso) {
$cursos[$index]['nombre'] = $curso['Curso']['nombreCurso'];
}
echo json_encode($cursos);
}
Doing this i get as a response on the console:
Object{data: "", status: 200, config: Object, statusText: "OK"}
If I do this:
var_dump($cursos);
I get the following:
array (size=3)
0 =>
array (size=1)
'nombre' => string 'Tecnologias de la informacion' (length=29)
1 =>
array (size=1)
'nombre' => string 'Propedeutico' (length=12)
2 =>
array (size=1)
'nombre' => string 'Lectura y redaccion' (length=19)
However, if i do the following:
$test = array(array('nombre' => 'Propedeutico'), array('nombre' => 'Tecnologias'));
echo json_encode($test);
I do get that array as a response...
What am I missing? I know this might be a silly mistake, but I haven't been able to solve it so far...
Thanks a lot!!
I made it work doing a little modification, since the result of the request brings back a string with accents, example: "Tecnología", i had to utf8_encode each one of the elements like this:
public function lookForCourses () {
$this->autoRender = false;
$cursosFind = $this->Curso->find('all', array('fields' => array('nombreCurso')));
$cursos = array();
foreach($cursosFind as $index => $curso) {
$cursos[$index]['nombre'] = utf8_encode($curso['Curso']['nombreCurso']);
}
echo json_encode($cursos);
}
Adding ut8_encode did the trick.

Using 'chunks' together with 'with' on Laravel query builder

dunno if this is possible at all.. I'm trying to query a large set of data with relations like so:
Parent::with([
'child' => function($query) {
$query->('published', '=', true);
$query->with('child.of.child', 'some.other.child');
$query->chunk(400, function($childs) {
// how is it now possible to add the $childs to the parent result??
});
}
]);
$parent = [];
Parent::with(
[
'childs' => function ($query) use (&$parent) {
$query->where('STATUS', '!=', 'DELETED');
$query->with('some.child', 'some.other.child');
$parent['models'] = $query->getParent()
->getModels();
$query->chunk(
400, function ($result) use ($query, &parent) {
$query->match($parent['models'], $result, 'child-relations-name');
});
}
])
->get();
Now $parent['models'] contains the tree with all the nested child relations... Dunno if this is the smartest way to do so, but it works for now.

Resources