2011-09-28 45 views

回答

26

count作品正是你所期望的,例如它counts all the elements in an array (or object)。但是你對包含四個元素的數組假設是錯誤的:

  • 「1」等於1,所以1 => "B"將覆蓋"1" => "A"
  • 由於您定義了1,下一個數字索引將爲2,例如, 「C」是2 => "C"
  • 當您指定2 => "D"時,您重寫了「C」。

所以你的數組將只包含1 => "B"2 => "D",這就是爲什麼count給人2.您可以驗證這一點是通過做print_r($a)如此。這將給

Array 
(
    [1] => B 
    [2] => D 
) 

請再次通過http://www.php.net/manual/en/language.types.array.php

5

你可以使用這個例子來理解怎麼算遞歸陣列

<?php 
$food = array('fruits' => array('orange', 'banana', 'apple'), 
       'veggie' => array('carrot', 'collard', 'pea')); 

// recursive count 
echo count($food, COUNT_RECURSIVE); // output 8 

// normal count 
echo count($food); // output 2 

?> 

Source

1

您創建的陣列只能在這兩個元素,因此計數返回2.您將要覆蓋的元素,看看你的陣列使用什麼:

print_r($a);