Returns the array dimension (number of layers)-PHP source code.

Source: Internet
Author: User
Returns an array dimension (number of layers) call.

$arr = array(array(1,2=>array(1,2,3)),2=>array(1=>array(array(array())),2),3);echo GetArrLv($arr);

For example, if implode is a multi-dimensional array, an error is returned. of course, we can use an array similar to array_search (true, array_map ('is _ array', $ arr )) this method is used to determine whether it is 2-dimension + (for example, please Hold the performance control ).

Next, we use print_r as the media.

/*** Returns the array dimension (level) * @ author echo * @ param array $ arr * @ return int */function GetArrLv ($ arr) {if (is_array ($ arr) {# recursively set all values to NULL. Objective 1. eliminate fictitious layers such as array ("array (\ n ()"), 2. print_r output is lightweight. array_walk_recursive ($ arr, function (& $ val) {$ val = NULL ;}); $ ma = array (); # Match [blank] from the beginning of the line to the first left brace, enable the multi-line switch 'M' preg _ match_all ("'^ \ (| ^ \ s + \ ('m", print_r ($ arr, true), $ ma ); # callback to string length // $ arr_size = array_map ('strlen', current ($ ma )); # Remove the maximum length and the length occupied by the left parenthesis. // $ max_size = max ($ arr_size)-1; # The array layer spacing should be 8 space columns, here we need to add 1 because the first layer of left brackets printed by print_r are at the beginning of the row/return $ max_size/8 + 1; return (max (array_map ('strlen ', current ($ ma)-1)/8 + 1;} else {return 0 ;}}
2.Call it
$arr = array(array(1,2=>array(1,2,3)),2=>array(1=>array(array(array())),2),3);echo GetArrLv($arr);

The preceding figure shows the returned array dimension (number of layers). For more information, see PHP Chinese website (www.php1.cn )!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.