2010-01-23 62 views
18

有沒有辦法確定PHP數組中有多少維?確定PHP數組中的維數

+0

可能重複[有沒有辦法找出「深」的PHP數組是什麼?](http://stackoverflow.com/questions/ 262891/is-there-a-way-to-find-out-how-deep-a-php-array) – jeremy 2016-03-22 06:26:00

回答

16

尼斯的問題,這裏是a solution I stole from the PHP Manual

function countdim($array) 
{ 
    if (is_array(reset($array))) 
    { 
     $return = countdim(reset($array)) + 1; 
    } 

    else 
    { 
     $return = 1; 
    } 

    return $return; 
} 
+13

這不完全正確。因爲它只測試數組的第一個元素。所以當你確定它是一個均勻分佈的數組數組時,這隻會給出預期的結果。您必須遍歷所有元素才能真正瞭解可變深度。 (或者,也許我不知道的一些漂亮的遍歷算法) – 2010-01-23 06:21:17

4

你可以試試這個:

$a["one"]["two"]["three"]="1"; 

function count_dimension($Array, $count = 0) { 
    if(is_array($Array)) { 
     return count_dimension(current($Array), ++$count); 
    } else { 
     return $count; 
    } 
} 

print count_dimension($a); 
+0

不錯的一個,謝謝 – 2016-10-26 18:11:17

1

最喜歡的程序和麪向對象的語言,PHP本身不實現多維數組 - 它使用嵌套數組。

其他人提出的遞歸函數很混亂,但最接近答案。

C.

1

這一個適用於陣列,其中每個維度不具有相同類型的元素。它可能需要遍歷所有元素。

 
$a[0] = 1; 
$a[1][0] = 1; 
$a[2][1][0] = 1; 

function array_max_depth($array, $depth = 0) { 
    $max_sub_depth = 0; 
    foreach (array_filter($array, 'is_array') as $subarray) { 
     $max_sub_depth = max(
      $max_sub_depth, 
      array_max_depth($subarray, $depth + 1) 
     ); 
    } 
    return $max_sub_depth + $depth; 
} 
0

Some issues with jumping from one function to another in a loop in php


糾正這種雙重功能會去每個數組的最後一維在$ a,當它不是一個數組了它會響應它確實給循環的數量用分隔符|來到那裏。 這個代碼的缺點是它只有回聲,不能被返回(以正常的方式)。

function cc($b, $n) 
{ 
    $n++.' '; 
    countdim($b, $n); 

} 
function countdim($a, $n = 0) 
{ 
    if(is_array($a)) 
    { 
     foreach($a as $b) 
     { 
      cc($b, $n); 
     } 
    }else 
    { 
     echo $n.'|'; 
    } 
} 
countdim($a); 

這裏我做了回功能,但..其從HTML返回然後「GET」回PHP的按鈕點擊..我不知道任何其他方式,使其工作.. 所以才命名您的陣列$ a並按下按鈕:/

$max_depth_var = isset($_REQUEST['max_depth_var']) ? $_REQUEST['max_depth_var'] : 0; 
?> 
<form id="form01" method="GET"> 
<input type="hidden" name="max_depth_var" value="<?php 
function cc($b, $n) 
{ 
    $n++.' '; 
    bb($b, $n); 
} 
function bb($a, $n = 0) 
{ 
    if(is_array($a)) 
    { 
     foreach($a as $b)cc($b, $n); 
    }else 
    { 
    echo $n.', '; 
    }; 
} 
bb($a); ?>"> 
<input type="submit" form="form01" value="Get max depth value"> 
</form><?php 
$max_depth_var = max(explode(', ', rtrim($max_depth_var, ","))); 
echo "Array's maximum dimention is $max_depth_var."; 
+0

不要只是發佈代碼;提供解釋。 – reformed 2017-09-06 03:41:40