【问题标题】:PHP Count function with Associative Array带有关联数组的 PHP 计数函数
【发布时间】:2011-11-26 19:14:27
【问题描述】:

有人可以向我解释一下 count 函数是如何与下面的数组一起工作的吗?

我的想法是输出 4 的以下代码,因为那里有 4 个元素:

$a = array 
(
  "1" => "A",
   1=> "B",
   "C",
   2 =>"D"
);

echo count($a);

【问题讨论】:

    标签: php count associative-array


    【解决方案1】:

    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

    【讨论】:

      【解决方案2】:

      您可以通过此示例了解 count 如何与递归数组一起使用

      <?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

      【讨论】:

        【解决方案3】:

        您创建的数组中只有两个元素,因此计数返回 2。您正在覆盖元素,以查看数组中的内容:

        print_r($a);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-11-06
          • 2021-09-09
          • 2021-03-23
          • 2022-10-08
          • 1970-01-01
          • 2015-12-30
          • 1970-01-01
          相关资源
          最近更新 更多