如何从print_r打印的数组的输出创建一个数组?我有一个数组:$a = array('foo' => 'fooMe');我这样做:print_r($a);打印:Array ( [foo] => printme )有没有功能,所以在做的时候:needed_function(' Array ( [foo] => printme )');我会把阵列拿array('foo' => 'fooMe');回来吗?
3 回答
幕布斯6054654
TA贡献1876条经验 获得超7个赞
小唯快跑啊
TA贡献1863条经验 获得超2个赞
对于使用子阵列的数组输出,ninetwozero提供的解决方案将不起作用,您可以尝试使用适用于复杂数组的此函数:
<?php
$array_string = "
Array
(
[0] => Array
(
[0] => STATIONONE
[1] => 02/22/15 04:00:00 PM
[2] => SW
[3] => Array
(
[0] => 4.51
)
[4] => MPH
[5] => Array
(
[0] => 16.1
)
[6] => MPH
)
[1] => Array
(
[0] => STATIONONE
[1] => 02/22/15 05:00:00 PM
[2] => S
[3] => Array
(
[0] => 2.7
)
[4] => MPH
[5] => Array
(
[0] => 9.61
)
[6] => MPH
)
)
";print_r(print_r_reverse(trim($array_string)));function print_r_reverse(&$output){
$expecting = 0; // 0=nothing in particular, 1=array open paren '(', 2=array element or close paren ')'
$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;
}
}
// Added this to allow for multi line strings.
else if (!empty($trim) && $expecting == 2)
{
// 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;}?>有一个小bug,如果你有一个空值(空字符串),它会嵌入到之前的值中。
添加回答
举报
0/150
提交
取消
