In laravel, I have a working code block where I loop an array and within it I call an email list. However, there are certain elements in the array that have a specific email that I want to add to it. So I always want the existing email config list to be used no matter what, but if the array element of the person has an email key I want to add that to the emails array, if that makes sense.
Here is the existing code as it:
$items = array(
array(
"employee" => 123,
"name" => "Tom",
"email" => "Tom#sitepoint.com"
),
array(
"employee" => 234,
"name" => "Sally"
),
array(
"employee" => 345,
"name" => "Rob"
),
array(
"employee" => 456,
"name" => "Ed"
"email" => "ed#sitepoint.com"
),
array(
"employee" => 567,
"name" => "Barbara"
)
);
foreach($items as $item){
//if there is an override email in the command
if($this->option('email') != 'default') {
if(!filter_var($this->option('email'), FILTER_VALIDATE_EMAIL)) {
$this->error('invalid email:'.$this->option('email'));
return;
}
$emails = ['to'=>[$this->option('email')],'cc'=>[]];
} else {
//This line works as is but I want a condition so that if the array element has and "email" key, I add that value as well
$emails = config('emails.printouts.employeePrintOuts');
//here I would need to add the array value (if email is set in that element)
}
...
}
The part in question is only in the 'else' block. How can I properly do this so that only certain array elements will have an email key and if they do I add it to the emails array that is always using the config list?
As mentioned in comments, you can use array_key_exist() function to check that $items contain email key.
Also to fullfil $emails['to'] subarray only in case that it doesn't contain current $items['email'] you may use in_array() function.
Solution:
if ( array_key_exist('email', $item) && !in_array($item['email'], $emails['to']) )
{
//TODO validate $item['email'] here
$emails['to'][] = $item['email'];
}
//Result $emails array will be looks like this:
[
'to' => [ "Tom#sitepoint.com", "ed#sitepoint.com" ],
'cc' => []
]
Related
I'm looking for a smart way to find out if my array of objects within an object has multiple name values or not to do a validation since it's only allowed to have one array name per inner array:
$elements = [];
$elements[18][20] = [
[
'name' => 'Color',
'value' => 'Red'
],
[
'name' => 'Color',
'value' => 'Green'
],
[
'name' => 'Size',
'value' => 'S'
]
];
$elements[18][21] = [
[
'name' => 'Size',
'value' => 'S'
],
[
'name' => 'Length',
'value' => '20'
],
];
error_log( print_r( $elements, true ) );
So the object 20 for example is invalid because it has 2 colors with the same value. At the end I was hoping to get a result array containing 1 duplicate name. This way I can output them like: "You have at least one duplicate name: Color".
My first idea was to loop over the array and do a second loop. This way it was possible to receive the inner arrays containing the stuff. Now I was able to add every name to another array. After this I was able to use count() and array_intersect() to receive a value of x which showed me if there are duplicates or not.
Now I had a count, but not the actual value to display. Before I use a semi-good solution, I was hoping to get any ideas here how I can make it better!
This loop will generate your expected output:
foreach($elements[18] as $index => $element){
//Get all the elements' names
$column_key = array_column($element, 'name');
//Get the count of all keys in the array
$counted_values = array_count_values($column_key);
//Check if count is > 1
$filtered_array = array_filter($counted_values, fn($i) => $i > 1);
//If the filter is not empty, show the error
if(!empty($filtered_array)){
//get the key name
$repeated_key = array_key_first($filtered_array);
echo "You have at least one duplicate name: {$repeated_key} at index {$index}";
break;
}
}
It relies in the array_count_values function.
I have a rather simple script which uses a hardcoded array to load employees and their names and emails, then loops through each array element and sets an email address array so that it emails each report to the right person.
The issue is that each employee will have multiple emails, so I need to have the email key consume multiple addresses and then when I loop below it would need to email that report to multiple people
What's the best way to alter this?
$items = array(
array(
"employee" => 5273,
"name" => "Jon Doe",
"email" => "emp1#newSite.com"
),
array(
"employee" => 5274,
"name" => "Jane Doe",
"email" => "emp2#newSite.com"
),
);
foreach($items as $item){
$dealerNum = $item["employee"];
$dealerName = $item["name"];
$emails = config('emails.employees');
if (array_key_exists('email',$item)){
$emails['to'][] = $item['email'];
}
}
Make the email value an array. Then you can append it to $emails['to'].
There's no need to call config('emails.employees') every time through the loop. Call it once before the loop, then add to the emails inside the loop.
$items = array(
array(
"employee" => 5273,
"name" => "Jon Doe",
"email" => ["emp1#newSite.com"]
),
array(
"employee" => 5274,
"name" => "Jane Doe",
"email" => ["emp2#newSite.com", "emp3#newSite.com"]
),
);
$emails = config('emails.employees');
foreach($items as $item){
$dealerNum = $item["employee"];
$dealerName = $item["name"];
if (array_key_exists('email',$item)){
$emails['to'] += $item['email'];
}
$emails['to'] = array_unique($emails['to']); // remove duplicates
}
I want to use if for this array :
$options[] = array( "name" => __('slider Settings','wordpresstools'),
"desc" => __('','wordpresstools'),
"id" => $shortname."_favSlider",
"std" => "",
"type" => "select",
"options" => array(
'option1' => 'test',
'option2' => 'test 2',
'option3' => 'test 3'
));
if this select option = option1
echo " Test ";
I have more $options , but I want to if just for that option ( Slider Settings )
Thanks .
Maybe the problem in your code are those brackets after $options. That way you append a new array element to the collection which means you have to test for something like this:
// Assuming your code creates the first array element
if ($options[0]['std'] == 'option1') {
// Do your stuff
}
If you don't need the square brackets in your first line of code it would look like this:
$options = array(/* Your values */);
if ($options['std'] == 'option1') {
// Do your stuff
}
$shortname='test';
$options = array( "name" => create_function('slider Settings','wordpresstools'),
"desc" => create_function('','wordpresstools'),
"id" => $shortname."_favSlider",
"std" => " I am here",
"type" => "select",
"options" => array(
'option1' => 'test',
'option2' => 'test 2',
'option3' => 'test 3'
));
echo "<pre>";
print_r($options['std']);
If i am right you try to create a constructor function there. In order to do something like that you must use create function. Read more details here The output of this code is printing std field as you want. The downside is that this method will be deprecated in PHP 7.2 so maybe you can find another work around than creating functions inside an array.
Foreach loop on options
foreach($options['options'] as $k=>$v){
// Check value of key
if($k == 'option1'){
echo $v . "\n";
}
}
I'm not exactly sure what kind of implementation you need but this should be a decent start for however you're trying to use it. I'm not sure if you mean to always have option1, option2, option3, etc. set or if you're checking to see if they exist. If the prior, then you'd need to make a few slight changes; if the latter, then this should work fine as it will check every key value and it should only exist if the option is selected.
Given following collection/array:
[
"somename" => "test.test.be"
"anothername" => "test"
"yetanothername" => "testing"
"extrafield" => "extra",
"extrafield" => "extra",
]
When i retrieve this collection i always know the order of them, but i will not know the key-names. So what i want to do is transform this collection and change the keynames to my defined values.
For a non-associative array i would do something like
$trimmedCollection->transform(function ($item) {
return [
'email' => $item[0],
'first_name' => $item[1],
'surname' => $item[2],
];
});
But how would i handle this for the given collection? Also what to do with overflow items. Say i suddenly got 10 key-value pairs but only wrote a transform for 3 how would i transform all the overflow to a default key?
Edit:
For the overflow items i would like to assign all extra fields in the given array to be stored like so.
Below would be the final array:
[
"email" => "test.test.be"
"first_name" => "test"
"surname" => "testing"
"additional_fields" => ["key-name" => "extra","key-name" => "extra"]
]
Where the key-name is the original name of the key i retrieved.
You can use array_shift to remove the 1st element in the array for every known element, and add the remaining array to your additional_fields key:
$trimmedCollection->transform(function ($item) {
return [
'email' => array_shift($item), //$item[0]
'first_name' => array_shift($item), //$item[1]
'surname' => array_shift($item), //$item[2]
'additional_fields' => $item //all remaining items
];
});
You could do something like this to transform your selected keys. This retains the other values with their unchanged keys.
function replace_array_key(array &$item, $oldKey, $newKey)
{
$item[$newKey] = $item[$oldKey];
unset($item[$oldKey]);
}
$trimmedCollection->transform(function ($item) {
replace_array_key($item, 'somename', 'email');
replace_array_key($item, 'anothername', 'first_name');
replace_array_key($item, 'yetanothername', 'surname');
return $item;
});
You can even extend this to an array list of old and new key names and run it through and arrap_map.
I have a COLLECTION collflokks in MongoDB, sample Document is :-
{
"_id" : "b_8AUL",
"f_name" : "Pizza. Hut",
"f_lat" : "22.7523513",
"f_lng" : "75.9225847",
"c_uid" : "33",
"f_type" : NumberLong(3),
"members" : [
"42",
"43"
]
}
Within the "members" array , I want to add Arrays like {id:42,name:Mark} , {id:43,name:Hughes}
Currently i'm adding just ids(eg.42,43). I'm only concerned about the new data as it will have new ids .Please suggest.
Earlier I was using this code to push into the members Array:
$flokkCollection = 'collFlokks';
$flokkCollection->update(
array("_id" => $f_handle),
array('$push' => array("members" => $u_id))
);
Well if what you are asking here is "replacing your existing data" then you need to "loop" the results from the collection and "replace" the array content that exists with your new format.
There are likely smarter ways to approach this, but you are not really giving us all the required information in your question, so I can only answer in the basic terms.
Presuming you have:
$required = array(
array(array("id" => "42"), array("name" => "Mark")),
array(array("id" => "43"), array("name" => "Hughes"))
);
As input, then you do something like this:
function myMapper($v) {
return $v["id"];
}
$mapped = array_map("myMapper",$required);
foreach( $mapped as $value) {
$filtered = array_values(
array_filter($required,function($k) {
return $k["id"] == $value;
})
)[0];
collection.update(array(
array("members" => $value),
array('$set' => array(
"members.$" => $filtered
))
));
}
Which should use the positional $ operator to find the matched "position" of the array element by the value used in the "query" portion of the update statement, then in the "update" portion of that statement $set that current array index to the new value at the "filtered" content index from the original input array.
Outside of PHP. We call these inner elements "objects" and not "arrays" which is a PHP notation trait. Key/value things are "objects" and "lists" are "arrays".