用文件存储数组的三种常用方法

  在Coding过程中经常会碰到用文件存储数组的情况,比如做缓存文件等等等等。下面总结下文件存储数组的三种常用方法。

  一、return array


<?php //存储数组的文件array.php 
return Array ( 
    "db_host1" => 123,
     "db_host2" => 123, 
    "db_host3" => 123,
     "db_host4" => 123,
     "db_host5" => 123,
     "db_host6" => 123,
     "db_host7" => 123,
     "db_host8" => 123,
     "db_host9" => 123,
     "db_host10" => 123,
     "db_host11" => 123,
     "db_host12" => 123,
     "db_host13" => 123,
     "db_host14" => 123,
     "db_host15" => 123,
     "db_host16" => 123 );
 ?>

使用进直接require ‘array.php’ 即可:


<?
$file = './arr.php';
$arr  = require $file;
?>

  二、序列化

<?php
//存储数组的文件ser.php
return
'a:16:{s:8:"db_host1";s:3:"123";s:8:"db_host2";s:3:"123";s:8:"db_host3";s:3:"123";s:8:"db_host4";s:3:"123";s:8:"db_host5";s:3:"123";s:8:"db_host6";s:3:"123";s:8:"db_host7";s:3:"123";s:8:"db_host8";s:3:"123";s:8:"db_host9";s:3:"123";s:9:"db_host10";s:3:"123";s:9:"db_host11";s:3:"123";s:9:"db_host12";s:3:"123";s:9:"db_host13";s:3:"123";s:9:"db_host14";s:3:"123";s:9:"db_host15";s:3:"123";s:9:"db_host16";s:3:"123";}';
?>

调用后对文件进行反序列化即可得到数组:


<?
$file = './ser.php';
$arr  = unserialize(require $file);
?>

三、存为ini配置文件形式

  先举个例子:文件名ini.php


<?php 
exit;
?>
db_host1 =123
db_host2 =123
db_host3 =123
db_host4 =123
db_host5 =123
db_host6 =123
db_host7 =123
db_host8 =123 
db_host9 =123
db_host10 =123
db_host11 =123
db_host12 =123
db_host13 =123
db_host14 =123
db_host15 =123
db_host16 =123

  用parse_ini_file直接对文件进行解析即可得到数组:


<?
$file = './ini.php';
$arr  = parse_ini_file($file2);
?>

  上面介绍的ini配置文件的写法只是最简单的形式,想看精彩的写法请看php.ini 🙂 ,可以在ini文件中加注释、可以使其返回的数组为二维数组。

  

  总结下上面三种方法,经测试在效率上差别不是很大;当数组是一维的情况下本人更喜欢用ini的形式——直观;如果要求返回的数组较复杂的话ini形式就不太适应,可以用return array形式或序列化。


( ! ) Warning: Missing argument 1 for cwppos_show_review(), called in /data/www/enjoyphp/wp-content/themes/flat/content-single.php on line 29 and defined in /data/www/enjoyphp/wp-content/plugins/wp-product-review/includes/legacy.php on line 18
Call Stack
#TimeMemoryFunctionLocation
10.0001355192{main}( ).../index.php:0
20.0001355480require( '/data/www/enjoyphp/wp-blog-header.php' ).../index.php:17
30.232010172280require_once( '/data/www/enjoyphp/wp-includes/template-loader.php' ).../wp-blog-header.php:19
40.233810243424include( '/data/www/enjoyphp/wp-content/themes/flat/single.php' ).../template-loader.php:74
50.333710801440get_template_part( ).../single.php:5
60.333710801960locate_template( ).../general-template.php:167
70.333710802056load_template( ).../template.php:643
80.333710802440require( '/data/www/enjoyphp/wp-content/themes/flat/content-single.php' ).../template.php:686
90.340710789312cwppos_show_review( ).../content-single.php:29

发表评论

电子邮件地址不会被公开。 必填项已用*标注