保定网站建设,网站推广,网站优化服务,保定专业的PHP网站制作机构!

你用哪个函数查看数据结构(PR)

发表于:2008年08月11日 18时  作者:dx_andy

当一个项目中存在很多相关联的数据时,我们通常的做法是将其整理为一个数组。在开发阶段我们需要随时关注数组的结构与数据,这时就要用到PHP打印数组的几个函数(print_r,var_dump,var_export),到底哪个比较适合您当前的需求,看下文!

假如我们有如下一个数组(友情链接数组):

$links数组结构
  1. $links = array(   
  2.     0 => array(   
  3.         ‘url’ => ‘www.phplamp.com’,   
  4.         ‘title’ => ‘phplamp站’,   
  5.         ‘target’ => ‘_blank’,   
  6.         ‘type’ => ‘font’,   
  7.     ),   
  8.     1 => array(   
  9.         ‘url’ => ‘www.phplamp.org’,   
  10.         ‘title’ => ‘phplamp博客站’,   
  11.         ‘target’ => ‘_blank’,   
  12.         ‘type’ => ‘font’,   
  13.     ),   
  14. );  

一、print_r() : 清晰的列出数组的讯息,数组的索引用“[]”包裹,使用此函数后数组的指针会移到最后。

Print_r()
  1. echo ‘<pre>’;   
  2. print_r($links);   
  3. echo ‘</pre>’;   
  4.   
  5. /**  
  6.  * 返回结果  
  7. Array  
  8. (  
  9.     [0] => Array  
  10.         (  
  11.             [url] => www.phplamp.com  
  12.             [title] => phplamp站  
  13.             [target] => _blank  
  14.             [type] => font  
  15.         )  
  16.  
  17.     [1] => Array  
  18.         (  
  19.             [url] => www.phplamp.org  
  20.             [title] => phplamp博客站  
  21.             [target] => _blank  
  22.             [type] => font  
  23.         )  
  24.  
  25. )  
  26. */  

二、var_dump() : 打印数组的详细结构与信息,包括表达式的类型与值。数组将递归展开值,通过缩进显示其结构。

PHP代码
  1. echo ‘<pre>’;   
  2. var_dump($links);   
  3. echo ‘</pre>’;   
  4.   
  5. /**  
  6.  * 返回结果  
  7.  array(2) {  
  8.   [0]=>  
  9.   array(4) {  
  10.     ["url"]=>  
  11.     string(15) ”www.phplamp.com”  
  12.     ["title"]=>  
  13.     string(10) ”phplamp站”  
  14.     ["target"]=>  
  15.     string(6) ”_blank”  
  16.     ["type"]=>  
  17.     string(4) ”font”  
  18.   }  
  19.   [1]=>  
  20.   array(4) {  
  21.     ["url"]=>  
  22.     string(15) ”www.phplamp.org”  
  23.     ["title"]=>  
  24.     string(16) ”phplamp博客站”  
  25.     ["target"]=>  
  26.     string(6) ”_blank”  
  27.     ["type"]=>  
  28.     string(4) ”font”  
  29.   }  
  30. }  
  31. */  

三、var_export() : 输出或返回数组的结构信息,此信息为PHP合法的代码,简单的缓存中我经常用到此函数。

PHP代码
  1. echo ‘<pre>’;   
  2. var_export($links);   
  3. echo ‘</pre>’;   
  4.   
  5. /**  
  6.  * 返回结果  
  7.  array (  
  8.   0 =>   
  9.   array (  
  10.     ’url’ => ’www.phplamp.com’,  
  11.     ’title’ => ’phplamp站’,  
  12.     ’target’ => ’_blank’,  
  13.     ’type’ => ’font’,  
  14.   ),  
  15.   1 =>   
  16.   array (  
  17.     ’url’ => ’www.phplamp.org’,  
  18.     ’title’ => ’phplamp博客站’,  
  19.     ’target’ => ’_blank’,  
  20.     ’type’ => ’font’,  
  21.   ),  
  22. )  
  23. */  

先记录这点,有空再补~!

 订阅“PHPLAMP博客”方便及时获取网站内容

PHPLAMP博客是专注于网站建设,搜索引擎研究,网站推广,网站优化的IT博客。

发表一下您对本文的意见