PHP - How to remove empty entries of an array recursively?

前端 未结 6 1144
臣服心动
臣服心动 2020-12-15 22:58

I need to remove empty entries on multilevel arrays. For now I can remove entries with empty sub-arrays, but not empty arrays... confused, so do I... I think the code will h

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-15 23:37

    Here is my solution, it will remove exactly specified list of empty values recursively:

    /**
     * Remove elements from array by exact values list recursively
     *
     * @param array $haystack
     * @param array $values
     *
     * @return array
     */
    function array_remove_by_values(array $haystack, array $values)
    {
        foreach ($haystack as $key => $value) {
            if (is_array($value)) {
                $haystack[$key] = array_remove_by_values($haystack[$key], $values);
            }
    
            if (in_array($haystack[$key], $values, true)) {
                unset($haystack[$key]);
            }
        }
    
        return $haystack;
    }
    

    You can use it like this:

    $clean = array_remove_by_values($raw, ['', null, []]);
    

    Note, it removes empty sub arrays if you pass [] as one of values.

提交回复
热议问题