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
]
);
Related
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.
I work in Laravel, I get the students Ids and I count how many absents, but how I can select only students who have 2-time absents?
App\StudentReport::pluck('absent')->collapse()->pluck('students')->collapse()->countby();
Output:
=> Illuminate\Support\Collection {#3095
all: [
"5d9ddb3512e5e17be04be12c" => 2,
"5d9ddb3512e5e17be04be12d" => 2,
"5da2411cf0d7276fab6ae8e5" => 13,
"5da2411cf0d7276fab6ae8f0" => 13,
"5da2411cf0d7276fab6ae8fd" => 1,
],
}
You need to filter your data like this:
App\StudentReport::pluck('absent')->collapse()->pluck('students')->collapse()->countby()->filter(function($item){return $item ==2;});
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.
If you have an array of hashes such as:
t = [{'pies' => 1}, {'burgers' => 1}, {'chips' => 1}]
what would be an efficient and readable way to add 1 to the value of a hash that has a particular key such as 'pies'?
Here's one way to increment the value(s) of an array's hashes based on a desired key:
t = [{ 'pies' => 1 }, { 'burgers' => 1 }, { 'chips' => 1 }]
t.each { |hash| hash['pies'] += 1 if hash.key?('pies') }
# => [{"pies"=>2}, {"burgers"=>1}, {"chips"=>1}]
Hope this helps!
If you know there's only one hash that could take the key 'pies' then you can use find and increase the value it has, like:
array = [{ 'pies' => 1 }, { 'burgers' => 1 }, { 'chips' => 1 }]
pies_hash = array.find { |hash| hash['pies'] }
pies_hash['pies'] += 1
p array
# [{"pies"=>2}, {"burgers"=>1}, {"chips"=>1}]
Enumerable#find will try to find the element that satisfies the block and stops the iteration when it returns true.
You're using the wrong data structure. I recommend using a Hash.
Each item on your menu can only have one count (or sale), that is each item is unique. This can be modelled with a hash with unique keys (the items) and their corresponding values (the counts).
t = {'pies' => 1, 'burgers' => 1, 'chips' => 1}
Then we can access keys and add to the count:
t['pies'] += 1
t #=> t = {'pies' => 2, 'burgers' => 1, 'chips' => 1}
Given an array of keys and an array of values, I can create a hash with these keys and values using #hash{#keys} = #vals.
However, I would like to do this for subkeys of a hash. This does not work: $h{"key"}{#subkeys} = #vals.
$ perl -MData::Dumper -le '
#subkeys=(qw(one two));
#vals=(1, 2);
$hash{"key"}{#subkeys} = #vals;
for (qw(subkeys vals)) {
print "$_ :\n", Dumper(\#{$_})
};
print "hash: \n", Dumper(\%hash);'
What I get is:
subkeys :
$VAR1 = [
'one',
'two'
];
vals :
$VAR1 = [
1,
2
];
hash:
$VAR1 = {
'key' => {
'2' => 2
}
};
If this is possible, what would be the correct syntax to get the following Dumper result:
$VAR1 = {
'key' => {
'one' => 1,
'two' => 2
}
};
It does work when using a temporary hash:
perl -MData::Dumper -le '#subkeys=(qw(one two)); #vals=(1, 2); #tmp{#subkeys}=#vals; $hash{"key"}={%tmp}; print Dumper(\%hash)'
But I suspect I'm just missing the correct syntax to get it without the %tmp hash.
You need to close the hashref part in a #{} slice "cast".
#{$hash{"key"}}{#subkeys} = #vals;