Laravel Collection - Return Array of Objects - arrays

So I am trying to return an array of objects with my Laravel collection using the following code:
/**
* View a user's chat rooms.
*
* return \Illuminate\Http\Response|\Laravel\Lumen\Http\ResponseFactory\
*/
public function viewChatRooms()
{
$user = Auth::user(); // #var User $user
$username = $user->username;
$rooms = Room::with('messages')->get()
->filter(function ($val) use ($username){
foreach ($val->users as $user) {
if($user === $username){
return $val;
}
}
});
return response(['rooms' => $rooms]);
}
Instead of returning an array of objects, the response returns the following:
{
"rooms": {
"0": {...},
"3": {...}
}
}
This is the desired result:
{
"rooms": [
{...},
{...}
]
}
Kind of stumped by this, could some one guide me in the right direction?

You Can use array_value function of PHP when returning response like this:
return response()->json([
'rooms' => array_values($rooms->toArray())
]);
Laravel Collection Methods for Getting only values of Collection
https://laravel.com/docs/5.8/collections#method-values
So
return response()->json([
'rooms' => $rooms->values()->toArray()
]);

The issue was that I didn't rebase the array since it skipped a few keys. I fixed it by simply using array_values() like so:
$rooms = Room::with('messages')->get()
->filter(function ($val) use ($username){
foreach ($val->users as $user) {
if($user === $username){
return $val;
}
}
});
return response(['rooms' => array_values($rooms->toArray())]);

I think that you will find that doing this within your DB query will be better performance wise.
Something like this:
$rooms = Room::whereHas('users', function(user) use ($username) {
return $user == $username
})
->with('messages')
->get();

To return an array of objects, you can use the all method.
Instead of returning a collection of objects, it returns an array of objects.
For example, User::all(); returns an Eloquent collection which is structured like so:
[
{App\User},
{App\User},
{App\User}
]
Whereas, the other answers suggest using ->toArray() which returns an array of arrays, not an array of objects, e.g.:
[
[
'id' => 123,
'name' => 'example'
...
],
[
...
]
]

Related

Convert Laravel array collection to array

I was updating may images array which is found in following format:
[
"d756d3d2b9dac72449a6a6926534558a.jpg",
"b607aa5b2fd58dd860bfb55619389982.jpg",
"f937c8fddbe66ab03c563f16d5cfa50c.jpg"
]
So to delete a single image d756d3d2b9dac72449a6a6926534558a.jpg from this array column I used the filter method like below:
$collection = collect($imageColumn)->filter(
function ($valueTobeDeleted) use ($array) {
return !in_array($valueTobeDeleted, $array);
}
);
so after filter I wan to update my database with the new collection, but the new collection is in a map format like below
array:2 [
1 => "b607aa5b2fd58dd860bfb55619389982.jpg"
2 => "f937c8fddbe66ab03c563f16d5cfa50c.jpg"
]
the problem is i don't need those keys 1, and 2 my expectation was
array:2 [
"b607aa5b2fd58dd860bfb55619389982.jpg"
"f937c8fddbe66ab03c563f16d5cfa50c.jpg"
]
How can I achieve my expectation? How can I convert them to array?
Because you are using a Collection, you can do ->values() at the end so you convert all keys into integer keys and beginning from 0, like a normal non-associative array:
$collection = collect($imageColumn)->filter(
function ($valueTobeDeleted) use ($array) {
return !in_array($valueTobeDeleted, $array);
}
)
->values();
In order to re-index an array, you can use the array_values PHP function:
$arr = array_values($arr);
This will fix the keys.
Use array_values to get a an array of that associatve array.
$collection = collect($imageColumn)->
$filtered = filter(function ($valueTobeDeleted) use ($array) {
return !in_array($valueTobeDeleted, $array);
});
$filtered = array_values($filtered);

How to Group array then iterate

I have trouble with my project.
First, I have a data like this : https://jsoneditoronline.org/?id=c6d15407962e4d1b986435ad3c283b4e
Then I group the data using this:
private function _group_by($array, $key) {
$new = [];
foreach ($array as $value) {
$new[$value[$key]][] = $value;
}
return $new;
}
$key = 'water_id'
After that the following result is like this: https://jsoneditoronline.org/?id=72991d45938c49a38900703feb3a60e7
From result above I cant iterate the data (I want to iterate since beginning). So, I want to able iterate the data, it is something wrong with my group by array function ? If you understand what I want, please help.
You can use collections to manipulate arrays or Traversable objects.
Grouping in CakePHP's Collection
use Cake\Collection\Collection;
private function _group_by($array, $key) {
$collection = new Collection($array);
return $collection->groupBy('water_id')->toArray();
}
You tagged this as being a Laravel App, right? Check out Collections: https://laravel.com/docs/5.6/collections.
$result = null;
collect($array)->groupBy($keyName)->each(function ($group, $key) use (&$result) {
foreach ($group as $element => $index) {
//Do something to $result.
}
});
Depending on your circumstances, map or transform might be more appropriate than each.

Reading JSON into arrays in Angular (HttpClient)

i am trying to read JSON into different arrays using HttpClient for the use in Echarts, but since i am a newbie i couldn't find how to fill JSON into the different arrays.
the part code i used so far was:
....
label: Array<any>;
data: Array<any>;
tooltip: Array<any>;
constructor(private http: HttpClient) {
this.getJSON().subscribe(data => {
this.data=data.data;
this.label=data.label;
this.tooltip=data.tooltip;
console.log(data)
});
}
public getJSON(): Observable<any> {
return this.http.get("./assets/JSONData/TeamProgress.json")
}
the JSON file is formatted like this:
[{"label":"0","data":"0","tooltip":"0"},
{"label":"1","data":"-1","tooltip":" tooltip1"},
{"label":"2","data":"-1","tooltip":" tooltip2"},
...etc
i want to be able to get all labels of JSON in one array, and all data in another array, and all tooltips in a third array.
it would be great if you can help me.
thanks
First the result of that file should be a valid JSON structure aka (an object with key-values) you can group the array under a key called per example result
{
"result": [
{"label":"0","data":"0","tooltip":"0"},
{"label":"1","data":"-1","tooltip":" tooltip1"},
{"label":"2","data":"-1","tooltip":" tooltip2"},
//....Etc
]
}
Then you can access the data and filter it using map as below:
this.getJSON().subscribe((data:any) => {
this.label = data.result.map(element =>
// if you want to return an array of objects
{return {"label": element.label}}
// or if you want to return the raw values in an array, just do
element.label
});
this.data = data.result.map(element => {
return {"data": element.data}
});
this.tooltip = data.result.map(element => {
return {"tooltip": element.tooltip}
})
})

How to parse through FB Graph API friends list array for specific value, ID?

I successfully loaded the friends array containing more arrays into a variable. But how do I iterate through it to take only the id's out?
I used:
$friends = $facebook->api('/me/friends/');
It returns a multidimensional array like so:
array(1) { ["name"] => "Username" ["id"] => "User ID #"}
array(2) { ["name"] => "Username" ["id"] => "User ID #"}
...and so on...
Any help would be appreciated! Thanks.
Results of Graph API almost always contain data property which is contain all the response data, to get only the friends ids you can look over it in such way:
// If all you need is users ids, specify it in fields url argument
$friends = $facebook->api('/me/friends/?fields=id');
$data = $friends['response'];
$friendsIds = array();
for ($data as $user){
$friendsIds[] = $user['id'];
}
Try:
$yourIdArr = array();
foreach($yourFriendArray as $key => $val) {
if("id" == $key) {
array_push($yourIdArr, $val);
}
}

How do I change my data accessing way from data[key] to data->key in laravel collection?

I got a data structure like below that is created by laravel collection put() function.
Code:
$array= collect();
$array->put($id, "1");
$array->put($name, "test");
Result:
{
"id": "1",
"name": "test"
}
How can I get the value with this syntax $array->id instead of this $array['id']?
Check this answers, https://stackoverflow.com/a/56565951/641611
$arr = ['id' => 3];
$arrToObject = (object) $arr;
echo $arrToObject->id;

Resources