如何计算动态创建的数组的长度?

时间:2014-03-14 09:42:48

标签: php arrays algorithm loops

我有一个数组

dump($data);
*************************************

    array(10) {
      ["12-male"] => string(1) "2"
      ["11-male"] => string(1) "2"
      ["10-female"] => string(1) "2"
      ["16-female"] => string(1) "2"
      ["9-male"] => string(1) "2"
      ["17-male"] => string(1) "4"
      ["14-male"] => string(1) "4"
      ["15-female"] => string(1) "4"
      ["13-female"] => string(1) "5"
      ["18-female"] => string(1) "6"
    }

******************************************

我动态地从上面的数组中得到子数组

$rooms = array();
foreach ($data as $key => $value) {
    $rooms['room'.$value][] = $key;
        $rooms['room'.$value]['count'] = sizeof($rooms['room'.$value]);
}

        dump($rooms);

******************************************

我得到了这个结果

Dump => array(4) {
  ["room2"] => array(6) {             //array size=6
    [0] => string(7) "12-male"
    ["count"] => int(6)               //count of array size=6
    [1] => string(7) "11-male"
    [2] => string(9) "10-female"
    [3] => string(9) "16-female"
    [4] => string(6) "9-male"
  }
  ["room4"] => array(4) {             //array size=4
    [0] => string(7) "17-male"
    ["count"] => int(4)               //count of array size=4
    [1] => string(7) "14-male"
    [2] => string(9) "15-female"
  }
  ["room5"] => array(2) {             //array size=2
    [0] => string(9) "13-female"
    ["count"] => int(1)               //count of array size=1 (the problem here)
  }
  ["room6"] => array(2) {             //array size=2
    [0] => string(9) "18-female"
    ["count"] => int(1)               //count of array size=1 (the problem here)
  }
}

我的问题是,计数在前2次迭代后正确返回,之后计数总是显示1,无论数组的大小。 我也尝试了count()但结果是一样的。

2 个答案:

答案 0 :(得分:5)

你可以这样做:

$rooms = array();
foreach ($data as $key => $value) {
    if (!isset($rooms['room'.$value])) {
         $rooms['room'.$value] = array('count' => 0);
    }
    $rooms['room'.$value][] = $key;
    $rooms['room'.$value]['count']++;
}

但您无需将count添加到数组中。

答案 1 :(得分:3)

计数的原因是从room2和room4你在第一次迭代时插入'count',然后在后续迭代'count'包含在sizeof()请求中。对于房间5和房间6,因为它们只被迭代一次sizeof()只被调用一次,在'count'被插入到数组之前,所以它不是{count'的索引,不包括在{{1}的结果中对于那些物品。