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

2022-08-30 10:24:57

我有一个数组:

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

而我做:

print_r($a);

哪些打印:

Array ( [foo] => printme )

有没有函数,所以在做的时候:

needed_function('    Array ( [foo] => printme )');

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


答案 1

我实际上写了一个函数,将“字符串数组”解析为实际数组。显然,它有点黑客,但它适用于我的测试用例。下面是指向 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;
        }

    }
?>

答案 2

如果要将数组存储为字符串,请使用序列化 [docs]取消序列化 [docs]

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