php Get all values from multidimensional associative array

后端 未结 3 1801
醉梦人生
醉梦人生 2021-01-25 00:22

how can i get all values from multidimensional associative array I dont want to use print_r want to control my array put all the value in normal array with unique values my arr

相关标签:
3条回答
  • 2021-01-25 00:24

    array_walk is an option, but here's another option if you want to try something a bit more coded by yourself, solving this problem recursively

    This will flatten any n-max level array into a single array that contains all the values of all the sub arrays (including the initial array itself)

    <?php
    $array = array(
    1 => array(1, 2, 3, 4 => array(
    1, 2, 3, 4
    )),
    4, 5);
    function recurse_values($array) {
        if (is_array($array)) {
            $output_array = array();
            foreach ($array as $key=>$val) {
                $primitive_output = recurse_values($val);
                if (is_array($primitive_output)) {
                    $output_array = array_merge($output_array, $primitive_output);
                }
                else {
                    array_push($output_array, $primitive_output);
                }
            }
            return $output_array;
        }
        else {
            return $array;
        }
    }
    print_r(recurse_values($array));
    ?>
    

    If you need unique values, at the end you can add a array_unique to do this.

    0 讨论(0)
  • 2021-01-25 00:30

    Are you asking how you can "flatten" this multi-dimensional array into a one dimension? Possible solutions to similar problems... How to Flatten a Multidimensional Array?

    0 讨论(0)
  • 2021-01-25 00:33

    You can use array_walk

    $array = array(...); //your values here
    function output($item, $key) {
         echo $key . ' =>' . $item;
    }
    array_walk($array, 'output');
    
    0 讨论(0)
提交回复
热议问题