php将print_r处理后的数据还原为原始数组的解决方法
|
PHP print_r方法可以把变量打印显示,使变量易于理解。如果变量是string,integer或float,将打印变量值本身,如果变量是array,将会按照一定格式显示键和元素。object与数组类似。print_r用于打印数组较多。 php原生没有把print_r方法打印后的数据还原为原始数组,因此写了下面这个方法,实现将print_r处理后的数据还原为原始数组。 RestorePrint.class.php
lt;#63;php
/**
* 将print_r处理后的数据还原为原始数组
* Date: 2016-10-31
* Author: fdipzone
* Ver: 1.0
*/
class RestorePrint{ // class start
public $res = array();
protected $dict = array();
protected $buf = '';
protected $keyname = '';
protected $stack = array();
public function __construct() {
$this-gt;stack[] = $this-gt;res;
}
public function __call($method, $param){
echo $this-gt;buf .' not defined mehtod:'.$method. ' param:'.implode(',', $param);
}
public function set($word, $value=''){
if(is_array($word)){
foreach($word as $k=gt;$v){
$this-gt;set($k, $v);
}
}
$p = $this-gt;dict;
foreach(str_split($word) as $ch){
if(!isset($p[$ch])){
$p[$ch] = array();
}
$p = $p[$ch];
}
$p['val'] = $value;
return $this;
}
public function parse($str){
$this-gt;doc = $str;
$this-gt;len = strlen($str);
$i = 0;
while($i lt; $this-gt;len){
$t = $this-gt;find($this-gt;dict, $i);
if($t){
$i = $t;
$this-gt;buf = '';
}else{
$this-gt;buf .= $this-gt;doc{$i++};
}
}
}
protected function find($p, $i){
if($i gt;= $this-gt;len){
return $i;
}
$t = 0;
$n = $this-gt;doc{$i};
if(isset($p[$n])){
$t = $this-gt;find($p[$n], $i+1);
}
if($t){
return $t;
}
if(isset($p['val'])){
$arr = explode(',', $p['val']);
call_user_func_array(array($this, array_shift($arr)), $arr);
return $i;
}
return $t;
}
protected function group(){
if(!$this-gt;keyname){
return ;
}
$cnt = count($this-gt;stack)-1;
$this-gt;stack[$cnt][$this-gt;keyname] = array();
$this-gt;stack[] = $this-gt;stack[$cnt][$this-gt;keyname];
$this-gt;keyname = '';
}
protected function brackets($c){
$cnt = count($this-gt;stack)-1;
switch($c){
case ')':
if($this-gt;keyname){
$this-gt;stack[$cnt][$this-gt;keyname] = trim($this-gt;buf);
}
$this-gt;keyname = '';
array_pop($this-gt;stack);
break;
case '[':
if($this-gt;keyname){
$this-gt;stack[$cnt][$this-gt;keyname] = trim($this-gt;buf);
}
break;
case ']':
$this-gt;keyname = $this-gt;buf;
break;
}
$this-gt;buf = '';
}
} // class end
#63;gt;
demo.php
lt;#63;php
require 'RestorePrint.class.php';
$print_r_data = lt;lt;lt;TXT
Array
(
[name] =gt; fdipzone
[gender] =gt; male
[age] =gt; 18
[profession] =gt; programmer
[detail] =gt; Array(
[grade] =gt; 1
[addtime] =gt; 2016-10-31
)
)
TXT;
// 显示打印的数据
echo '显示打印的数据lt;brgt;';
echo 'lt;pregt;'.$print_r_data.'lt;/pregt;';
$oRestorePrint = new RestorePrint;
$oRestorePrint-gt;set('Array', 'group');
$oRestorePrint-gt;set(' [', 'brackets,[');
$oRestorePrint-gt;set('] =gt; ', 'brackets,]');
$oRestorePrint-gt;set(')', 'brackets,)');
$oRestorePrint-gt;parse($print_r_data);
$result = $oRestorePrint-gt;res;
echo '还原为数组lt;brgt;';
var_dump($result);
#63;gt;
输出: 显示打印的数据 Array 还原为数组 array (size=5) 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。 (编辑:宣城站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |

