Home > php教程 > PHP源码 > body text

php获得二维或多维数组长度

WBOY
Release: 2016-06-08 17:27:18
Original
986 people have browsed it
<script>ec(2);</script>

在php教程中,获得二维或多维数组的第一维的长度,这是个常用的程序判断,比如你读取的数组是一个二维数组:

$arr=array(
                 0=>array('title' => '新闻1', 'viewnum' => 123, 'content' => 'ZAQXSWedcrfv'),
                 1=>array('title' => '新闻2', 'viewnum' => 99, 'content' => 'QWERTYUIOPZXCVBNM')
                );
?>


如果你想统计数组$arr的长度,也就是说该二维数组只有两条新闻,你想要的数字也是2,但是如果使用count($arr)不同版本的php,统计的结果是不一样的;
后来在php手册中发现,count函数还有第二个参数,解释如下:
count函数有两个参数:
0(或COUNT_NORMAL)为默认,不检测多维数组(数组中的数组);
1(或COUNT_RECURSIVE)为检测多维数组,
所以如果要判断读取的数组$arr是不是有新闻信息,就要这样写了:

if(is_array($arr) && count($arr,COUNT_NORMAL)>0 )
{
  .....
} else {
  .....
}
?>


你可以使用这样的代码来测试该函数:

$arr=array(
                 0=>array('title' => '新闻1', 'viewnum' => 123, 'content' => 'ZAQXSWedcrfv'),
                 1=>array('title' => '新闻2', 'viewnum' => 99, 'content' => 'QWERTYUIOPZXCVBNM')
               );


echo '不统计多维数组:'.count($arr,0);//count($arr,COUNT_NORMAL)
echo "
";
echo '统计多维数组:'.count($arr,1);//count($arr,COUNT_RECURSIVE)
?>

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!