PHP print_r 转换/还原为数组

来源:
http://stackoverflow.com/questions/7025909/how-create-an-array-from-the-output-of-an-array-printed-with-print-r

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

转载于:https://www.cnblogs.com/mslagee/p/6484411.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值