计算多维数组中的行/记录

时间:2013-04-03 15:15:08

标签: php arrays dynamic count

我有一组嵌套数组。

[data]是顶级数组。

较低级别的数组全部由增量数字标识,动态分配...基本上每个子数组都标识信息的行/记录。

如何提取子阵列的数量?我需要能够将此数据发布到数据库中。

子数组的数量是动态的,并且可以根据我正在解析的数据而改变。

 [data] => Array
        (
            [0] => Array
                (
                    [id] => 3475
                    [name] => Player1
                    [score] => 11870
                    [rank] => 213
                    [total_cities] => 2
                    [crown] => None
                    [alliance_id] => 134
                    [title] => Earl
                    [fame_total] => 509875
                    [fame_rank] => 381
                    [defeated_total] => 3436
                    [defeated_rank] => 376
                    [plunder_total] => 1388754
                    [plunder_rank] => 245
                )

            [1] => Array
                (
                    [id] => 3523
                    [name] => Player2
                    [score] => 1978
                    [rank] => 281
                    [total_cities] => 1
                    [crown] => None
                    [alliance_id] => 134
                    [title] => Baron
                    [fame_total] => 0
                    [fame_rank] => 448
                    [defeated_total] => 0
                    [defeated_rank] => 448
                    [plunder_total] => 0
                    [plunder_rank] => 436
                )

            [2] => Array
                (
                    [id] => 73
                    [name] => Player3
                    [score] => 1308
                    [rank] => 304
                    [total_cities] => 1
                    [crown] => None
                    [alliance_id] => 134
                    [title] => Marquess
                    [fame_total] => 5604153
                    [fame_rank] => 237
                    [defeated_total] => 37270
                    [defeated_rank] => 229
                    [plunder_total] => 68130
                    [plunder_rank] => 335
                )

3 个答案:

答案 0 :(得分:2)

我使用了Marc B和Thanos突出显示的方法的组合来获得我想要的结果

这是我使用的代码:

$count = 0;
foreach($data as $data=>$inner_array){
   $count = $count+1;
}

echo $count;

我用一个包含143个独特行的测试数据集来运行它,然后我得到了回声,所以生活很美好。

谢谢你们。

答案 1 :(得分:0)

最简单的方法:

$count = 0;
foreach($mainarray as $subarray)
   $count += count($subarray);
}

答案 2 :(得分:0)

我们假设$ data是你的主要数组: 这个打印每个内部数组的名称(0,1,2 ...为您的示例),然后计算每个子数组项:

echo "Number of sub-arrays: ".count($online_time); //optional
foreach($data as $inner_array=>$data_of_inner_array) {
echo $inner_array;
echo " --- ".count($data_of_inner_array);
echo "<br/>";
}

我假设输出

Number of sub-arrays: 3
0 --- 14
1 --- 14
2 --- 14