2010-01-23 7 views
18

PHP 배열에 몇 개의 차원이 있는지 확인하는 방법이 있습니까?PHP 배열의 차원 수 결정

+0

[가능한 PHP 배열을 찾는 방법이 있습니까?] (http://stackoverflow.com/questions/) 262891/is-there-a-way-to-find-out-how-a-php-array-is) – jeremy

답변

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

이것은 완전히 정확하지 않습니다. 왜냐하면 배열의 첫 번째 요소 만 테스트하기 때문입니다. 따라서 배열의 배열을 고르게 분배 할 때 예상되는 결과 만 얻을 수 있습니다. 가변 깊이를 진정으로 알기 위해서는 모든 요소를 ​​반복해야합니다. (또는 아마도 내가 알고있는 어떤 순회 탐색 알고리즘) –

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

좋은 하나, 감사합니다 –

1

을, PHP는 기본적으로 다차원 배열을 구현하지 않습니다 - 그것은 중첩 배열을 사용합니다.

다른 사람이 제안한 재귀 함수는 지저분하지만 대답에 가장 가까운 것입니다.

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

는 그 배열이 아닌 더 이상 그것에게 한 루프의 수를 에코 때이 두 기능은 $ A의 각 배열의 마지막 차원으로 이동합니다 Some issues with jumping from one function to another in a loop in php


에서 수정되었습니다 구획 문자로 거기에 가라. 이 코드의 단점은 에코이며 리턴 될 수 없다는 것입니다 (일반적인 방법으로).

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에서의 복귀 후 .. 나는 그것이 작동되도록하는 다른 방법을 잘 모릅니다 버튼 클릭에 PHP로 다시 "GET".. 그래서 그냥 배열 이름을 $ 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