How to run array_filter recursively in a PHP array?

前端 未结 6 1869
挽巷
挽巷 2020-11-29 11:16

Given the following array $mm

Array
(
    [147] => Array
        (
            [pts_m] => 
            [pts_mreg] => 1
            [pts         


        
6条回答
  •  执念已碎
    2020-11-29 12:19

    A better alternative

    One implementation that always worked for me is this one:

    function filter_me(&$array) {
        foreach ( $array as $key => $item ) {
            is_array ( $item ) && $array [$key] = filter_me ( $item );
            if (empty ( $array [$key] ))
                unset ( $array [$key] );
        }
        return $array;
    }
    

    I notice that someone had created a similar function except that this one presents, in my opinion, few advantages:

    1. you pass an array as reference (not its copy) and thus the algorithm is memory-friendly
    2. no additional calls to array_filter which in reality involves:
      • the use of stack, ie. additional memory
      • some other operations, ie. CPU cycles

    Benchmarks

    1. A 64MB array
      • filter_me function finished in 0.8s AND the PHP allocated memory before starting the function was 65MB, when function returned it was 39.35MB !!!
      • array_filter_recursive function recommended above by Francois Deschenes had no chance; after 1s PHP Fatal error: Allowed memory size of 134217728 bytes exhausted
    2. A 36MB array
      • filter_me function finished in 0.4s AND the PHP allocated memory before starting the function was 36.8MB, when function returned it was 15MB !!!
      • array_filter_recursive function succeeded this time in 0.6s and memory before/after was quite the same

    I hope it helps.

提交回复
热议问题