如何从print_r打印的数组的输出创建一个数组?

Joh*_*ar. 41 php arrays string variables type-conversion

我有一个数组:

$a = array('foo' => 'fooMe');
Run Code Online (Sandbox Code Playgroud)

我这样做:

print_r($a);
Run Code Online (Sandbox Code Playgroud)

打印:

Array ( [foo] => printme )
Run Code Online (Sandbox Code Playgroud)

有没有功能,所以在做的时候:

needed_function('    Array ( [foo] => printme )');
Run Code Online (Sandbox Code Playgroud)

我会把阵列拿array('foo' => 'fooMe');回来吗?

kar*_*ark 30

我实际上编写了一个将"stringed array"解析为实际数组的函数.显然,它有点hacky等等,但它适用于我的测试用例.这是http://codepad.org/idlXdij3上功能原型的链接.

对于那些不想点击链接的人,我也会内联发布代码:

<?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;
        }

    }
?>
Run Code Online (Sandbox Code Playgroud)

  • 对于简单数组,这是有效的,但是对于多维数组,它会失败.只需使用[this](http://www.php.net/manual/en/function.print-r.php#93529). (15认同)

Fel*_*ing 14

如果要将数组存储为字符串,请使用serialize [docs]unserialize [docs].

回答你的问题:不,没有内置函数可以print_r再次解析数组的输出.

  • 这个答案避免了为所提出的问题提供解决方案。我们必须假设 OP(以及找到此页面的其他研究人员)无法修改输入结构。(如果他们可以修改输入结构,SO 上还有很多其他页面描述了如何使用 `serialize`/`unserialize` 和 `json_encode()`/`json_decode()`。) (2认同)

Adr*_*uer 8

对于使用子阵列的数组输出,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;
}

?>
Run Code Online (Sandbox Code Playgroud)

有一个小bug,如果你有一个空值(空字符串),它会嵌入到之前的值中.


els*_*ooo 7

不,但您可以同时使用serializejson_*功能.

$a = array('foo' => 'fooMe');
echo serialize($a);

$a = unserialize($input);
Run Code Online (Sandbox Code Playgroud)

要么:

echo json_encode($a);

$a = json_decode($input, true);
Run Code Online (Sandbox Code Playgroud)


mak*_*kus 7

有一个很好的在线工具,它的名字是这样的:

print_r 到 json 在线转换器

从 JSON 对象到使用json_decode函数创建数组不远了:

要从中获取数组,请将第二个参数设置为 true。如果你不这样做,你会得到一个对象。

json_decode($jsondata, true);
Run Code Online (Sandbox Code Playgroud)


ajr*_*eal 6

你不能这样做print_r,
var_export应该允许类似的东西,但不完全是你要求的东西

http://php.net/manual/en/function.var-export.php

$val = var_export($a, true);
print_r($val);
eval('$func_val='.$val.';');
Run Code Online (Sandbox Code Playgroud)

  • 我认为他想知道这个函数是什么,以便他得到一个数组。 (2认同)
  • 看在上帝的份上,永远不要在生产代码中使用“eval”! (2认同)