iT邦幫忙

0

[PHP]請問如何計算一個陣列的維度

php

請問如何計算一個PHP陣列的維度呢?

saiue iT邦研究生 1 級 ‧ 2011-03-16 16:26:30 檢舉
不知道 foreach+function是否也可以使用
fillano iT邦超人 1 級 ‧ 2011-03-17 09:55:30 檢舉
當然可以阿,把property拆出來成為變數,method拆出來成為function也OK。只是用class來做這些事情比較不會干擾變數...如果是php5.3,也許可以用closure來做,這是另一種不靠class又不會干擾到global變數的解法。
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

4
fillano
iT邦超人 1 級 ‧ 2011-03-15 13:00:31
最佳解答

PHP並沒有真正的多維度陣列,只是Array中的元素可以是Array。

我想你恐怕需要寫一個函數或是類別,用遞迴的方式遍歷陣列元素,來計算出可能的維度。

例如:

<pre class="c" name="code">
<?php
class ArrayDim {
	private $_array;
	private $count=0;

	public $dimension=1;

	function __construct($a) {
		$this->_array = $a;
	}

	function check() {
		$this->check_rec($this->_array);
		return $this->dimension;
	}

	private function check_rec($_a=array()) {
		$this->count++;
		if($this->count>$this->dimension)
			$this->dimension = $this->count;
		foreach($_a as $v) {
			if(is_array($v)) {
				$this->check_rec($v);
			}
		}
		$this->count--;
	}
}
$a = array(array(1,3,5), 3, array(2,4), 4, array(1,array(1,6,4,array(2,4)),8,9));
$b = new ArrayDim($a);
print_r($a);
echo "<br>dimension: ".$b->check();
?>

我要發表回答

立即登入回答