问题
I have an array which consists of 7 days names. This array will be dynamic everytime. So i want to check which day is missing from an array. For ex,
[Monday,Tuesday,Thursday,Friday,Saturday,Sunday]
Here, the wednesday is missing so output should be wednesday
Sometimes there will be more then one day will be missing and sometimes none, so the output should be and array which will contain all missing days.
回答1:
you can compare two arrays with array_diff
. Example: https://3v4l.org/4g00a
回答2:
You can use array_diff function to get missing days.
$days = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];
$inputDays = ['Sunday','Friday'];
$missingDays = array_diff($days,$inputDays);
print_r($missingDays);
Output
Array
(
[0] => Monday
[1] => Tuesday
[2] => Wednesday
[3] => Thursday
[5] => Saturday
)
array_diff is case sensitive, you may need to convert string to lower case.
Demo
回答3:
Since you tagged both js and php but didn't specify which language you're using for this part of your code, here's a JS solution (which doesn't have a handy array_diff
function)
var days = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];
var input = ["Sunday","Friday"];
return days.filter(function(day) {return input.indexOf(day) < 0;});
来源:https://stackoverflow.com/questions/51347766/check-which-day-is-not-avaliable-in-php-array