How to create an array from output of var_dump in PHP?

前端 未结 6 1952
谎友^
谎友^ 2021-01-13 06:53

How can I parse the output of var_dump in PHP to create an array?

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-13 07:46

    Use var_export if you want a representation which is also valid PHP code

    $a = array (1, 2, array ("a", "b", "c"));
    $dump=var_export($a, true);
    echo $dump;
    

    will display

    array (
     0 => 1,
     1 => 2,
     2 => 
     array (
       0 => 'a',
       1 => 'b',
       2 => 'c',
     ),
    )
    

    To turn that back into an array, you can use eval, e.g.

    eval("\$foo=$dump;");
    var_dump($foo);
    

    Not sure why you would want to do this though. If you want to store a PHP data structure somewhere and then recreate it later, check out serialize() and unserialize() which are more suited to this task.

提交回复
热议问题