如果我有如下嵌套数组,如何检查任何dates
数组是否不为空?
$myArray = [
'1' => [ 'dates' => []],
'2' => [ 'dates' => []],
'3' => [ 'dates' => []],
...
]
我知道我可以通过执行foreach循环来检查此问题:
$datesAreEmpty = true;
foreach($myArray as $item) {
if (!empty($item['dates'])) {
$datesAreEmpty = false;
}
}
有没有更优雅的方式做到这一点?
答案 0 :(得分:0)
您需要分三步进行
答案 1 :(得分:0)
更优雅?不,我不这么认为。实际上,您可以在第一个非空值之后中断循环,以使此检查短路,这是一个微小的改进,但这是这样做的方法。
使用array_walk(肯定会在几分钟内提到)使用起来较慢且可读性较差;此外,还有一些棘手的序列化解决方案(通过strpos或regex查找非空日期字符串),但是应用它们并不会带来任何好处。
坚持使用此解决方案,并在第一次打击时稍事休息。 #chefstip;)
答案 2 :(得分:0)
使用count
的第二个参数将计算包括子数组在内的数组中的所有项目。并非像其他答案一样,它不能解决所有情况,并且具有一些尚不清楚的初始假设,但仍然:
// Suppose you have array of your structure
$myArray = [
'1' => ['dates' => []],
'2' => ['dates' => []],
'3' => ['dates' => []],
];
// compare
var_dump(count($myArray), count($myArray, true));
// you see `3` and `6`
// - 3 is count of outer elements
// - 6 is count of all elements
// Now if there're no other keys in subarrays except `dates`
// you can expect that `count` of all elements is __always__
// twice bigger than `count` of outer elements
// When you add some value to `dates`:
$myArray = [
'1' => ['dates' => ['date-1']],
'2' => ['dates' => []],
'3' => ['dates' => []],
];
// compare
var_dump(count($myArray), count($myArray, true));
// you see `3` (outer elements) and `7` (all elements)
// So, you have __not empty__ `dates` when `count` of all elements
// is more than doubled count of outer elements:
$not_empty_dates = 2 * count($myArray) < count($myArray, true);
// Of course if you have other keys in subarrays
// code should be changed accordingly, that's why
// it is not clear solution, but still it can be used
正在工作的小提琴https://3v4l.org/TanG4。
答案 3 :(得分:0)
可以使用array_filter迭代完成:
// This will be empty if all array elements are empty.
$filtered = array_filter($myArray, '_filter_empty');
/**
* Recursively remove empty elements from array.
*/
function _filter_empty($element) {
if (!is_array($element)) {
return !empty($element);
}
return array_filter($element, '_filter_empty');
}