比方说,我有一些源这个输出,其中我没有访问原始PHP创建数组:
Array
(
[products] => Array
(
[name] => Arduino Nano Version 3.0 mit ATMEGA328P
[id] => 10005
)
[listings] => Array
(
[category] =>
[title] => This is the first line
This is the second line
[subtitle] => This is the first subtitle
This is the second subtitle
[price] => 24.95
[quantity] =>
[stock] =>
[shipping_method] => Slow and cheap
[condition] => New
[defects] =>
)
[table_count] => 2
[tables] => Array
(
[0] => products
[1] => listings
)
)
现在我想输入的数据,并有一个算法重建原始的阵列,它正在打印,所以我就可以用我自己的应用程序。
目前,我在思考一个sub_str()
和提取数据,并适当地把它的正则表达式语句。 在我另外的头领,是有一个简单的方法,通过已经写好的代码或PHP的插件,我已经做到这一点了吗?
function print_r_reverse($in) {
$lines = explode("\n", trim($in));
if (trim($lines[0]) != 'Array') {
// bottomed out to something that isn't an array
return $in;
} else {
// this is an array, lets parse it
if (preg_match("/(\s{5,})\(/", $lines[1], $match)) {
// this is a tested array/recursive call to this function
// take a set of spaces off the beginning
$spaces = $match[1];
$spaces_length = strlen($spaces);
$lines_total = count($lines);
for ($i = 0; $i < $lines_total; $i++) {
if (substr($lines[$i], 0, $spaces_length) == $spaces) {
$lines[$i] = substr($lines[$i], $spaces_length);
}
}
}
array_shift($lines); // Array
array_shift($lines); // (
array_pop($lines); // )
$in = implode("\n", $lines);
// make sure we only match stuff with 4 preceding spaces (stuff for this array and not a nested one)
preg_match_all("/^\s{4}\[(.+?)\] \=\> /m", $in, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
$pos = array();
$previous_key = '';
$in_length = strlen($in);
// store the following in $pos:
// array with key = key of the parsed array's item
// value = array(start position in $in, $end position in $in)
foreach ($matches as $match) {
$key = $match[1][0];
$start = $match[0][1] + strlen($match[0][0]);
$pos[$key] = array($start, $in_length);
if ($previous_key != '') $pos[$previous_key][1] = $match[0][1] - 1;
$previous_key = $key;
}
$ret = array();
foreach ($pos as $key => $where) {
// recursively see if the parsed out value is an array too
$ret[$key] = print_r_reverse(substr($in, $where[0], $where[1] - $where[0]));
}
return $ret;
}
}
不是我的代码,发现这里的评论: print_r的 “马特”是主人
我也摸索出适合你的问题的解决方案,因为它是在这里对堆栈溢出问题重现一个非常有用的工具。 我的源位于: https://github.com/etalon/aprp
我做了一点不同:在您的字符串你不需要换行符,所以我通过字符行走。 一个disatvantage:如果有括号或括号中的数组值将无法正常工作。