Convert Laravel array collection to array - arrays

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

Related

How to count all data item array in laravel

How to count all data item array in laravel, please help me!. Thank you so much!
Output: 8
reduce()
The reduce method reduces the collection to a single value, passing
the result of each iteration into the subsequent iteration:
$count = collect([
(object)["views_back" => 3],
(object)["views_back" => 5]
])->reduce(function ($carry, $item) {
return $carry + $item->views_back;
});
var_export($count); // 8
Addendum
Alternatively, using native/vanilla PHP:
$count = array_sum(array_column([
(object)["views_back" => 3],
(object)["views_back" => 5]
], "views_back"));
var_export($count); // 8
When working with arrays in Laravel, it can be helpful to convert them to a Collection which provides some helper methods for arrays.
If all you want is the number of elements in the array use count.
If you want the sum of the views_back elements, use reduce.
$array = [
[
'views_back' => 3,
],
[
'views_back' => 5,
]
];
$count = collect($array)->count();
$sum = collect($array)->reduce(function ($carry, $element) {
return $carry + $element['views_back'];
});
dd($count, $sum);
In the above $count is 2 and $sum is 8.
If your original data is json (as you've used a json tag), you will need to convet the data to an array first:
$array = json_decode($json, true);
You can use laravel collection method sum() method to write smaller code and make it easier to read.
$data = [
(object)["views_back" => 3],
(object)["views_back" => 5]
];
collect($data)->sum('views_back');
Converting array to collection can be CPU costly depending on the size of the input array. In that case #steven7mwesigwa vanilla PHP answer would be the best solution.

Converting Ruby array of array into a hash

I have an array of arrays as below :
[
["2021-07-26T11:38:42.000+09:00", 1127167],
["2021-08-26T11:38:42.000+09:00", 1127170],
["2021-09-26T11:38:42.000+09:00", 1127161],
["2021-07-25T11:38:42.000+09:00", 1127177],
["2021-08-27T11:38:42.000+09:00", 1127104]
]
What i want to have as the output :
{
"2021-July" => [["2021-07-26T11:38:42.000+09:00", 1127167],["2021-07-25T11:38:42.000+09:00", 1127177]],
"2021-August" => [["2021-08-26T11:38:42.000+09:00", 112717],["2021-08-27T11:38:42.000+09:00", 112710]],
"2021-September" => ["2021-09-26T11:38:42.000+09:00", 112716]
}
I want to create the hash key year-month format based on the date value in each array element. What would be the easiest way to do this?
use group_by
date_array = [["2021-07-26T11:38:42.000+09:00", 1127167],["2021-08-26T11:38:42.000+09:00", 112717],["2021-09-26T11:38:42.000+09:00", 112716],["2021-07-25T11:38:42.000+09:00", 1127177],["2021-08-27T11:38:42.000+09:00", 112710]]
result = date_array.group_by{ |e| Date.parse(e.first).strftime("%Y-%B") }
date_array = [["2021-07-26T11:38:42.000+09:00", 1127167],["2021-08-26T11:38:42.000+09:00", 112717],["2021-09-26T11:38:42.000+09:00", 112716],["2021-07-25T11:38:42.000+09:00", 1127177],["2021-08-27T11:38:42.000+09:00", 112710]]
result_date_hash = Hash.new([])
date_array.each do |date|
formatted_date = Date.parse(date.first).strftime("%Y-%B")
result_date_hash[formatted_date] += date
end
Output:
puts result_date_hash
=>
{"2021-July"=>["2021-07-26T11:38:42.000+09:00", 1127167, "2021-07-25T11:38:42.000+09:00", 1127177],
"2021-August"=>["2021-08-26T11:38:42.000+09:00", 1127170, "2021-08-27T11:38:42.000+09:00", 1127104],
"2021-September"=>["2021-09-26T11:38:42.000+09:00", 1127161]}

Laravel Collection - Return Array of Objects

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'
...
],
[
...
]
]

Unique values in MongoDb array

I am trying find unique ObjectIds from monogdb ObjectId array using filter. For some reason I am not getting unique array back. Is there is some other way to get unique array back ?
var objIds = [ 5ad3509fbb426a4f4a382754,
5ad3509fbb426a4f4a382752,
5ad3509fbb426a4f4a382754,
5ad3509fbb426a4f4a382751
]
Here is the filter code
objIds = objIds.filter((x, i, a) => a.indexOf(x) == i)
I am expecting following array after filter
[ 5ad3509fbb426a4f4a382754,
5ad3509fbb426a4f4a382752,
5ad3509fbb426a4f4a382751
]
If you are passing in an array and the elements inside the array is a string then this should work.
function getUniqueValues(arr) {
return arr.filter((e, i) => arr.indexOf(e) === i)
}
you can use lodash's uniq method to do this easily.
const { uniq } = require("lodash");
var objIds = [
"5ad3509fbb426a4f4a382754",
"5ad3509fbb426a4f4a382752",
"5ad3509fbb426a4f4a382754",
"5ad3509fbb426a4f4a382751"
];
console.log(uniq(objIds));
will give the following output
[ '5ad3509fbb426a4f4a382754',
'5ad3509fbb426a4f4a382752',
'5ad3509fbb426a4f4a382751' ]

How to filter object from array by value and using the value to omit another array or objects?

I have a array, which has the bunch of object, i would like to filter the object by 'name' value, again i would like to omit those object from another array of object using underscore.
I know that we can do using earch, but i am not getting the proper approach to do this both..
any one help me to do this?
example :
incoming array:
var incomingArray = [
{"name":"apple"},
{"name":"orange"},
{"name":"dog"},
{"name":"cat"},
{"name":"egle"}
];
filter keys:
var omit = ['orange' ,'dog'];
//i need to check whether 'orange' or 'dog' are exist, if so..
var filtered = _.filter(incomingArray, function(obj, i){
return obj.name === omit[i]['name'];//this is wrong i need to loop again how?
});
var anotherArray = [
{"name":"apple"},
{"name":"orange"},
{"name":"dog"},
{"name":"cat"},
{"name":"egle"}
]
return only the array without the omit like this:
var outgoingArray = [
{"name":"apple"},
{"name":"cat"},
{"name":"egle"} ]
how we could achieve this with proper approach?
demo
You were nearly there! Use indexOf to check that the name does not belong in the omit array:
var filtered = _.filter(incomingArray, function(obj) {
return omit.indexOf(obj.name) == -1;
});

Resources