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.
Related
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);
I'm trying to search a element in the array. When get it i need to append some element of the end of the array.
I try similar to this.
List dataModelo = allMakers //THIS IS THE MAIN ARRRAY
.where((modelo) =>
modelo["fabricante"] ==
fabricante["fabricante"])
.toList()
.addAll([
{
"id": 0,
"fabricante":
'Test,
"modelo":
'Test'
}
]);
But return
The expression here has a type of 'void', and therefore cannot be
used.
So anybody know how can i do that?
SOLUTION:
dataModelo = allMakers
.where((modelo) =>
modelo["fabricante"] ==
fabricante["fabricante"])
.followedBy([
{
"id": 0,
"fabricante":
'TEXT',
"modelo":
'TEXT'
}
]).toList();
Use cascade notation after the .where(/**/).toList() part.
e.g.
final arr = [1, 2, 3];
print(arr.where((a) => a > 2).toList()
..addAll([ 4, 5 ])); // returns [3, 4, 5]
In other words, adding another . to your .addAll part should do the trick.
I want to do something like php's array_push
I'm using Cakephp3 Configure Class and want to store a list of user ids that are notified. Like this:
Configure::write('Notified_Users', 1);
Configure::write('Notified_Users', 2);
But the value 2 overrides value 1.
Is there any way i can push data to this variable? and then later i can check if the selected user is in the list.
you can create an array also this way
Configure::write('Notified_Users.0', 1);
Configure::write('Notified_Users.1', 2);
or simply
Configure::write('Notified_Users', [1, 2]);
if you debug(Configure::read('Notified_Users')); you'll get
[
(int) 0 => (int) 1,
(int) 1 => (int) 2
]
Push data to this variable:
$notified_users = [];
array_push($notified_users,1);
Configure::write('Notified_Users', $notified_users);
Check if the selected user is in the list:
if (in_array(1, Configure::read('Notified_Users')))
{
echo "Match found";
}
else
{
echo "Match not found";
}
Try this:
Configure::write('Notified_Users', [1, 2, 3]);
or
Configure::write('Notified_Users',
[
'0' => 1,
'1' => 2,
'2' => 3
]
);
I have an array of arrays that I'd like to convert into json and output within another array. I have the following array:
weekdays = [["Monday",2],["Tuesday",4],["Thursday",5]]
I would like to include this array within a JSON output like so:
json_output = { :results => weekdays.count, :data => weekdays }
Right now I get this, which just doesn't look right as there are not curly brackets around the "data" field...
{
"results": 2,
"data": [
["Monday", 2],
["Tuesday", 4],
["Thursday", 5]
]
}
Any help would be great!
The output is correct. Curly brackets are around hashes, but your data attribute is a nested array.
If you want to convert a nested array into a hash, just call to_h on it:
{ :results => weekdays.count, :data => weekdays.to_h }
Better to convert it to hash manually.
weekdays = [["Monday",2],["Tuesday",4],["Thursday",5]]
hash_weekdays = Hash.new
weekdays.each do |item|
hash_weekdays[item[0]] = item[1]
end
hash_weekdays #=> {"Monday"=>2, "Tuesday"=>4, "Thursday"=>5}
This is the code snippet I am working with:
my %photo_details = (
'black_cat' => (
('size' => '1600x1200', 'position' => -25),
('size' => '1280x1024', 'position' => 25),
('size' => '800x600', 'position' => 0),
),
'race_car' => (
('size' => '1600x1200', 'position' => 10),
('size' => '800x600', 'position' => 5),
),
);
my $photo = 'black_cat';
foreach my $photo_detail ($photo_details{$photo})
{
my $size = $photo_detail{'size'};
my $position = $photo_detail{'position'};
print ("size = $size, position = $position\n");
}
What I am expecting to get is:
size = 1600x1200, position = -25
size = 1280x1024, position = 25
size = 800x600, position = 0
What I do get is:
Use of uninitialized value $size in concatenation (.) or string at C:\Test.pl line 23.
Use of uninitialized value $position in concatenation (.) or string at C:\Test.pl line 23.
size = , position =
The foreach statement is clearly wrong as not only are there no values for $size and $position, it has only gone through the loop once instead of three times. I have tried all sorts of variants of variable prefixes and found none that work.
What am I doing wrong?
Here is some updated code, with an explanation below:
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my %photo_details = (
'black_cat' => [
{'size' => '1600x1200', 'position' => -25},
{'size' => '1280x1024', 'position' => 25},
{'size' => '800x600', 'position' => 0},
],
'race_car' => [
{'size' => '1600x1200', 'position' => 10},
{'size' => '800x600', 'position' => 5},
],
);
print Dumper( %photo_details );
foreach my $name ( keys %photo_details ) {
foreach my $photo_detail ( #{ $photo_details{$name} } ) {
my $size = $photo_detail->{'size'};
my $position = $photo_detail->{'position'};
print Dumper( $photo_details{$photo} );
print ("size = $size, position = $position\n");
}
}
I've replaced some of your parentheses with square and curly brackets. In Perl, square brackets give you a reference to an anonymous array, and curly brackets denote a reference to an anonymous hash. These are called anonymous because there's no explicit variable name for the anonymous array or hash.
As Perl data structures make you store a reference to a hash rather than the actual hash, you need these to construct the references. You can do this in two steps like this:
my #array = ( 1, 2, 3 );
my $array_ref = \#array;
my %hash = ( 'one' => 1, 'two' => 2, 'three' => 3 );
my $hash_ref = \%hash_ref;
To get data out of $array_ref and $hash_ref, you need the -> operator:
print $array_ref->[0], "\n";
print $hash_ref->{one}, "\n";
You don't need the quotes inside of the {} when referencing a hash key, although some people consider quotes on a hash key to be good practice.
I added an example of iteration over the entire data structure as an example rather than just looking at one reference. Here's the first line:
foreach my $name ( keys %photo_details ) {
The keys method returns all of the keys in a hash, so that you can get them in order. The next line iterates over all of the photo_detail hashrefs in %photo_details:
foreach my $photo_detail ( #{ $photo_details{$photo} } ) {
The #{ $photo_details{$photo} } de-references the reference $photo_details{$photo} into an array, which you can iterate over it with foreach.
The last thing that I added is a call to Data::Dumper, a very useful module distributed with Perl that prints out data structures for you. This is very handy when building up data structures like this, as is its closely related cousin Data::Dumper::Simple. This module is unfortunately not distributed with Perl, but I prefer its output as it includes variable names.
For some further reading about how to build up complex data structures using references, check out perlreftut.
First of all, always start every script or module with:
use strict;
use warnings;
You will get more warning messages and sooner, which greatly helps debugging.
I cannot duplicate your error: when I put that code into a file and run it with no additional flags, I get: size = , position =. There is no $size variable in the code you printed, so the error message does not match.
Nevertheless, you are declaring your data structures incorrectly. Hashes and arrays can
only contain scalar values, not lists: so if you want to nest an array or
a hash, you need to make it a reference. See perldoc perldata, perldoc perldsc
and perldoc perlreftut for more about data structures and references.
my %photo_details = (
black_cat => [
{ size => '1600x1200', position => -25 },
{ size => '1280x1024', position => 25 },
{ size => '800x600', position => 0 },
],
race_car => [
{ size => '1600x1200', position => 10 },
{ size => '800x600', position => 5 },
],
);
foreach my $photo_detail (#{$photo_details{black_cat}})
{
my $size = $photo_detail->{size};
my $position = $photo_detail->{position};
print ("size = $size, position = $position\n");
}
There's really only one thing you have to worry about, and that's the top level of the data structure. After that, you just use the right indexing syntax for each level:
If you have a regular hash, you access the key that you want then line up the additional indices for each level after it:
%regular_hash = ...;
$regular_hash{$key}[$index]{$key2};
If you have a reference, you do almost the same thing, but you have to start off with the initial dereference with an arrow, ->, after the top-level reference. After that it's the same indexing sequence:
$hash_ref = ...;
$hash_ref->{$key}[$index]{$key2};
For all of the details, see Intermediate Perl where we explain reference syntax.