Alternative var_dump for PHP that allows limiting depth of nested arrays

风流意气都作罢 提交于 2019-12-23 07:55:35

问题


I try to use var_dump on command line with phpsh in order to get debugging information about some variable. But the variable contains a very deeply nested data structure. Therefore, using the default var_dump outputs too much information.

I want to limit the depth level of var_dump output. I found that XDebug's var_dump implementation allows depth limiting as described here: http://www.giorgiosironi.com/2009/07/how-to-stop-getting-megabytes-of-text.html

Unfortunately, I couldn't make this work neither. I don't know yet the reason for this. I am looking for if there are any alternative var_dump implementations to try.


回答1:


Check this :

function print_array($array,$depth=1,$indentation=0){
    if (is_array($array)){
                    echo "Array(\n";
        foreach ($array as $key=>$value){
            if(is_array($value)){
                if($depth){
                    echo "max depth reached.";
                }
                else{
                    for($i=0;$i<$indentation;$i++){
                        echo "&nbsp;&nbsp;&nbsp;&nbsp;";
                    }
                    echo $key."=Array(";
                    print_array($value,$depth-1,$indentation+1);
                    for($i=0;$i<$indentation;$i++){
                        echo "&nbsp;&nbsp;&nbsp;&nbsp;";
                    }
                    echo ");";
                }
            }
            else{
                for($i=0;$i<$indentation;$i++){
                    echo "&nbsp;&nbsp;&nbsp;&nbsp;";
                }
                echo $key."=>".$value."\n";
            }
        }
                    echo ");\n";
    }
    else{
        echo "It is not an array\n";
    }
}



回答2:


Here is the function for this issue:

function slice_array_depth($array, $depth = 0) {
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            if ($depth > 0) {
                $array[$key] = slice_array_depth($value, $depth - 1);
            } else {
                unset($array[$key]);
            }
        }
    }

    return $array;
}

Use this function to slice an array to depth you need, than simply var_dump() or print_r() the sliced array :)




回答3:


json_encode takes a depth argument. Do this:

echo '<pre>' . json_encode($your_array, JSON_PRETTY_PRINT, $depth) . '</pre>';




回答4:


I'm just going to plug this var_dump alternative:

https://github.com/raveren/kint

obviously, depth limit is supported and enabled by default. You can furthermore, overcome it on the fly by prefixing Kint::dump($var); with a + - +Kint::dump($var); will not truncate based on depth.



来源:https://stackoverflow.com/questions/13396076/alternative-var-dump-for-php-that-allows-limiting-depth-of-nested-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!