代码之家  ›  专栏  ›  技术社区  ›  adam78

php-检查是否有任何嵌套数组不为空

  •  0
  • adam78  · 技术社区  · 7 年前

    如果我有如下嵌套数组,我如何检查 dates 数组不为空?

    $myArray =  [ 
        '1' =>  [ 'dates' => []],
    
        '2' =>  [ 'dates' => []],
    
        '3' =>  [ 'dates' => []],
    
        ...      
     ]
    

    我知道我可以通过foreach循环来检查:

    $datesAreEmpty = true;
    foreach($myArray as $item) {
    
      if (!empty($item['dates'])) {
          $datesAreEmpty = false;
      }
    }
    

    有没有比这更优雅的方法?

    3 回复  |  直到 7 年前
        1
  •  0
  •   Naveed Ramzan    7 年前

    你需要分三步做

    • 检查每个元素是否为数组()
    • 如果是,请检查大小($element)
    • 如果大于0,则为真,否则为假
        2
  •  0
  •   dkellner    7 年前

    更优雅?不,我不这么认为。实际上,你可以在第一次非空后断开回路,使这个检查短路,这是一个微小的改进,但这是实现的方法。

    使用array_walk(我相信几分钟后会提到)速度较慢,可读性较差;此外,序列化(通过strpos或regex查找非空日期字符串)也有一些棘手的解决方案,但应用它们不会获得任何好处。

    坚持这个解决方案,并在第一次击中时使用休息。#切夫斯蒂普;)

        3
  •  0
  •   u_mulder    7 年前

    使用第二个参数 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 .