有沒有辦法確定PHP數組中有多少維?確定PHP數組中的維數
回答
尼斯的問題,這裏是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;
}
這不完全正確。因爲它只測試數組的第一個元素。所以當你確定它是一個均勻分佈的數組數組時,這隻會給出預期的結果。您必須遍歷所有元素才能真正瞭解可變深度。 (或者,也許我不知道的一些漂亮的遍歷算法) – 2010-01-23 06:21:17
你可以試試這個:
$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);
不錯的一個,謝謝 – 2016-10-26 18:11:17
最喜歡的程序和麪向對象的語言,PHP本身不實現多維數組 - 它使用嵌套數組。
其他人提出的遞歸函數很混亂,但最接近答案。
C.
這一個適用於陣列,其中每個維度不具有相同類型的元素。它可能需要遍歷所有元素。
$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; }
在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.";
不要只是發佈代碼;提供解釋。 – reformed 2017-09-06 03:41:40
- 1. PHP中的多維數組
- 2. php訪問多維數組中的特定數組值
- 3. 多維數組的數據結構,其中維數在運行時確定
- 4. php比較單維數組中的多維數組值
- 5. PHP多維數組
- 6. PHP多維數組
- 7. PHP推維數組
- 8. PHP多維數組
- 9. PHP多維數組
- 10. 多維數組PHP
- 11. php二維數組
- 12. PHP多維數組
- 13. 多維數組 - PHP
- 14. PHP二維數組
- 15. PHP多維數組
- 16. Php多維數組
- 17. 多維數組php
- 18. PHP的多維數組簡單數組
- 19. PHP多維數組 - 數據
- 20. 數字多維數組php
- 21. php多維數組分組
- 22. PHP多維數組重組
- 23. PHP組多維數組?
- 24. 如何確定多維數組的每個維度的大小?
- 25. PHP - 替換多維數組中的數據,特定鍵
- 26. PHP - 確保多維數組中的某些值是唯一的
- 27. PHP多維數組按特定值
- 28. 如何在PHP中定義單維和多維數組?
- 29. 在php中實現多維數組的正確方法
- 30. PHP二維數組Javascript數組
可能重複[有沒有辦法找出「深」的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