和同事一起开发一个页面,因为进度问题,分工我帮写view层和一个稍微有点复杂的JS,同事那边controller层提供一个数组给我所需要的数据。因为同事有急事,当天走的匆忙,所以只给了我一个数组print_r后的字符串,因为数组较大,手动修改工作量很大,所以就google了下
找寻到如下代码,可以完美将字符串重新转换回数组。
特在此分享:
function print_r_reverse(&$output)
{
// 0=nothing in particular, 1=array open paren ‘(‘, 2=array element or close paren ‘)’
$expecting = 0;
$lines = explode("\n", $output);
$result = null;
$topArray = null;
$arrayStack = array();
$matches = null;
while (!empty($lines) && $result === null){
$line = array_shift($lines);
$trim = trim($line);
if ($trim == 'Array'){
if ($expecting == 0){
$topArray = array();
$expecting = 1;
}else{
trigger_error("Unknown array.");
}
}else if ($expecting == 1 && $trim == '('){
$expecting = 2;
}else if ($expecting == 2 && preg_match('/^\[(.+?)\] \=\> (.+)$/', $trim, $matches)){
// array element
list ($fullMatch, $key, $element) = $matches;
if (trim($element) == 'Array'){
$topArray[$key] = array();
$newTopArray =& $topArray[$key];
$arrayStack[] =& $topArray;
$topArray =& $newTopArray;
$expecting = 1;
}else{
$topArray[$key] = $element;
}
}else if ($expecting == 2 && $trim == ')'){
// end current array
if (empty($arrayStack)){
$result = $topArray;
}else{
// pop into parent array
// safe array pop
$keys = array_keys($arrayStack);
$lastKey = array_pop($keys);
$temp =& $arrayStack[$lastKey];
unset($arrayStack[$lastKey]);
$topArray =& $temp;
}
}else if (!empty($trim) && $expecting == 2){
// Added this to allow for multi line strings.
// Expecting close parent or element, but got just a string
$topArray[$key] .= "\n".$line;
}else if (!empty($trim)){
$result = $line;
}
}
$output = implode(n, $lines);
return $result;
}
/**
* @param string $output : The output of a multiple print_r calls, separated by newlines
* @return mixed[] : parseable elements of $output
*/
function print_r_reverse_multiple($output){
$result = array();
while (($reverse = print_r_reverse($output)) !== NULL){
$result[] = $reverse;
}
return $result;
}
$str = "Array(
[0] => Array(
[play_type_id] => 102
[play_type_name] => 三亚+其他
)
[1] => Array(
[play_type_id] => 172
[play_type_name] => 三亚一地
)
)";
$arr = print_r_reverse($str);
发表评论