php 如何从使用 print_r 打印的数组的输出创建数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7025909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How create an array from the output of an array printed with print_r?
提问by John Kar.
I have an array:
我有一个数组:
$a = array('foo' => 'fooMe');
and I do:
我这样做:
print_r($a);
which prints:
打印:
Array ( [foo] => printme )
Is there a function, so when doing:
有没有函数,所以在做的时候:
needed_function(' Array ( [foo] => printme )');
I will get the array array('foo' => 'fooMe');back?
我会拿回阵列array('foo' => 'fooMe');吗?
采纳答案by karllindmark
I actually wrote a function that parses a "stringed array" into an actual array. Obviously, it's somewhat hacky and whatnot, but it works on my testcase. Here's a link to a functioning prototype at http://codepad.org/idlXdij3.
我实际上编写了一个将“字符串数组”解析为实际数组的函数。显然,它有点老套,但它适用于我的测试用例。这是http://codepad.org/idlXdij3上一个功能原型的链接。
I'll post the code inline too, for those people that don't feel like clicking on the link:
对于那些不想点击链接的人,我也会内联发布代码:
<?php
/**
* @author ninetwozero
*/
?>
<?php
//The array we begin with
$start_array = array('foo' => 'bar', 'bar' => 'foo', 'foobar' => 'barfoo');
//Convert the array to a string
$array_string = print_r($start_array, true);
//Get the new array
$end_array = text_to_array($array_string);
//Output the array!
print_r($end_array);
function text_to_array($str) {
//Initialize arrays
$keys = array();
$values = array();
$output = array();
//Is it an array?
if( substr($str, 0, 5) == 'Array' ) {
//Let's parse it (hopefully it won't clash)
$array_contents = substr($str, 7, -2);
$array_contents = str_replace(array('[', ']', '=>'), array('#!#', '#?#', ''), $array_contents);
$array_fields = explode("#!#", $array_contents);
//For each array-field, we need to explode on the delimiters I've set and make it look funny.
for($i = 0; $i < count($array_fields); $i++ ) {
//First run is glitched, so let's pass on that one.
if( $i != 0 ) {
$bits = explode('#?#', $array_fields[$i]);
if( $bits[0] != '' ) $output[$bits[0]] = $bits[1];
}
}
//Return the output.
return $output;
} else {
//Duh, not an array.
echo 'The given parameter is not an array.';
return null;
}
}
?>
回答by Felix Kling
If you want to store an array as string, use serialize[docs]and unserialize[docs].
如果要将数组存储为字符串,请使用serialize[docs]和unserialize[docs]。
To answer your question: No, there is no built-in function to parse the output of print_rinto an array again.
回答您的问题:不,没有内置函数可以print_r再次将 的输出解析为数组。
回答by Adrian Cid Almaguer
For Array output with Subarrays, the solution provided by ninetwozerowill not work, you can try with this function that works with complex arrays:
对于带有子数组的数组输出,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;
}
?>
There is one tiny bug, if you have an empty value (empty string) it gets embedded in the value before.
有一个小错误,如果您有一个空值(空字符串),它会先嵌入到该值中。
回答by elslooo
No. But you can use both serializeand json_*functions.
不可以。但是您可以同时使用serialize和json_*函数。
$a = array('foo' => 'fooMe');
echo serialize($a);
$a = unserialize($input);
Or:
或者:
echo json_encode($a);
$a = json_decode($input, true);
回答by ajreal
you cannot do this with print_r,var_exportshould allow something similar, but not exactly what you asked for
你不能这样做print_r,var_export应该允许类似的东西,但不完全是你要求的
http://php.net/manual/en/function.var-export.php
http://php.net/manual/en/function.var-export.php
$val = var_export($a, true);
print_r($val);
eval('$func_val='.$val.';');
回答by makkus
There is a nice Online-Tool which does exatly what its name is:
有一个很好的在线工具,它的名字是这样的:
print_r to json online converter
From a JSON Object its not far to creating an array with the json_decodefunction:
从 JSON 对象到使用json_decode函数创建数组不远了:
To get an array from this, set the second paramter to true. If you don't, you will get an object instead.
要从中获取数组,请将第二个参数设置为 true。如果你不这样做,你会得到一个对象。
json_decode($jsondata, true);
回答by Raphos
I think my function is cool too, works with nested arrays:
我认为我的函数也很酷,适用于嵌套数组:
function print_r_reverse($input)
{
$output = str_replace(['[', ']'], ["'", "'"], $input);
$output = preg_replace('/=> (?!Array)(.*)$/m', "=> '',", $output);
$output = preg_replace('/^\s+\)$/m', "),\n", $output);
$output = rtrim($output, "\n,");
return eval("return $output;");
}
NB: better not use this with user input data
注意:最好不要将它与用户输入数据一起使用
回答by Khaldoon Masud
use
用
var_export(array('Sample array', array('Apple', 'Orange')));
Output:
输出:
array (
0 => 'Sample array',
1 =>
array (
0 => 'Apple',
1 => 'Orange',
),
)
回答by phoenix
Quick function (without checks if you're sending good data):
快速功能(不检查您是否发送了良好的数据):
function textToArray($str)
{
$output = [];
foreach (explode("\n", $str) as $line) {
if (trim($line) == "Array" or trim($line) == "(" or trim($line) == ")") {
continue;
}
preg_match("/\[(.*)\]\ \=\>\ (.*)$/i", $line, $match);
$output[$match[1]] = $match[2];
}
return $output;
}
This is the expected input:
这是预期的输入:
Array
(
[test] => 6
)

