如何在 PHP 中找到 2 维数组中的元素数?

是否有可用于获取二维数组列数的函数?我已经意识到该count()函数将显示二维数组中的行数,但我对获取每个数组中的列数很感兴趣。

我如何使用该count()函数或任何其他函数来获取包含在另一个数组中的数组中的元素数。这是正在使用的代码示例:


<?php

    $people = array(

            array("Rodrick","Java","PHP"),

            array("Jane","Python","Javascript"),

            array("Tom","Python","R"),

            array("Wangari","Ruby","Kotlin"),

    );


    for($row = 0 ; $row < count($people) ; $row++){

        echo "The Programmers ".$row;

        echo "<ol>";

        for($col = 0 ; $col < 3 ;$col++){

            echo "<li>".$people[$row][$col]."</li>";

        }

        echo "</ol>";

    }


三国纷争
浏览 150回答 3
3回答

蓝山帝景

您可以通过以下方式获取第二维的大小:$ncols = count($people[$row]);你的代码可能是这样的:<?php&nbsp; $people = array(&nbsp; &nbsp; &nbsp; &nbsp; array("Rodrick","Java","PHP"),&nbsp; &nbsp; &nbsp; &nbsp; array("Jane","Python","Javascript"),&nbsp; &nbsp; &nbsp; &nbsp; array("Tom","Python","R"),&nbsp; &nbsp; &nbsp; &nbsp; array("Wangari","Ruby","Kotlin"),&nbsp; );&nbsp; for($row = 0 ; $row < count($people) ; $row++){&nbsp; &nbsp; echo "The Programmers ".$row;&nbsp; &nbsp; echo "<ol>";&nbsp; &nbsp; $ncols = count($people[$row]);&nbsp; &nbsp; for($col = 0 ; $col < $ncols ; $col++){&nbsp; &nbsp; &nbsp; &nbsp; echo "<li>".$people[$row][$col]."</li>";&nbsp; &nbsp; }&nbsp; &nbsp; echo "</ol>";&nbsp; }?>

慕姐4208626

列数在此根据第一行确定。$numberOfColumns&nbsp;=&nbsp;count(reset($people));该计算可用于数值数组,也可用于关联数组。

千巷猫影

你真的需要知道嵌套数组的大小吗?这是foreach使用过的解决方案:$people = array(&nbsp; &nbsp; &nbsp; &nbsp; array("Rodrick","Java","PHP"),&nbsp; &nbsp; &nbsp; &nbsp; array("Jane","Python","Javascript"),&nbsp; &nbsp; &nbsp; &nbsp; array("Tom","Python","R"),&nbsp; &nbsp; &nbsp; &nbsp; array("Wangari","Ruby","Kotlin"),);foreach($people as $human){&nbsp; &nbsp; echo "<ol>";&nbsp; &nbsp; foreach($human as $data){&nbsp; &nbsp; &nbsp; &nbsp; echo "<li>".$data."</li>";&nbsp; &nbsp; }&nbsp; &nbsp; echo "</ol>";}
打开App,查看更多内容
随时随地看视频慕课网APP