2014-03-14 62 views
2

我有一個數組如何計算動態創建的數組的長度?

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(),但結果是一樣的。

回答

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添加到您的陣列。

+0

如果我想保持在同一個數組中的計數呢? – VostanAzatyan

+0

@ user3269869問題的答案是否會給你預期的結果? – xdazz

+0

是的,幫助了我很多,謝謝....但你能告訴我如何插入計數在我創建的數組? – VostanAzatyan

3

count這樣做的原因是,您在第一次迭代中從room2和room4插入'count',然後在後續迭代中,'count'包含在sizeof()請求中。對於房間5和房間6,因爲它們只被迭代一次sizeof()只在數組中插入'count'之前被調用一次,因此這些項目的sizeof的結果中不包括'count'的索引。