Jump to content

Recommended Posts

Hello. I have this array:

Array
(
    [0] => Rakel
    [1] => Dix
    [2] => Array
        (
            [0] => Barne
            [1] => Barn
            [2] => Array
                (
                    [0] => Tisse
                    [1] => Mann
                )

            [3] => Julenissen
        )

    [3] => Nisse
    [4] => Far
)

 

I wrote a function that transforms it to a string, but how do I turn it back?:

<?php
$array2string =  "0 => 'Rakel', 1 => 'Dix', array(0 => 'Barne', 1 => 'Barn', 0 => 'Barne', 1 => 'Barn', array(0 => 'Tisse', 1 => 'Mann')3 => 'Julenissen'3 => 'Julenissen')3 => 'Nisse', 4 => 'Far'";

$string2array = array($array2string);

//Unfortunatly this doesnt work because $array2string is a string. 
?>

 

 

How do I solve this problem?

 

Thanks,

Marius

It is a tad bit more complicated then that. Here is an example function found at print_r which can reverse the output produced by print_r (but you need the full output from it and not a jumbled mess like is in your code).

 

<?php
function print_r_reverse($in) {
    $lines = explode("\n", trim($in));
    if (trim($lines[0]) != 'Array') {
        // bottomed out to something that isn't an array
        return $in;
    } else {
        // this is an array, lets parse it
        if (preg_match("/(\s{5,})\(/", $lines[1], $match)) {
            // this is a tested array/recursive call to this function
            // take a set of spaces off the beginning
            $spaces = $match[1];
            $spaces_length = strlen($spaces);
            $lines_total = count($lines);
            for ($i = 0; $i < $lines_total; $i++) {
                if (substr($lines[$i], 0, $spaces_length) == $spaces) {
                    $lines[$i] = substr($lines[$i], $spaces_length);
                }
            }
        }
        array_shift($lines); // Array
        array_shift($lines); // (
        array_pop($lines); // )
        $in = implode("\n", $lines);
        // make sure we only match stuff with 4 preceding spaces (stuff for this array and not a nested one)
        preg_match_all("/^\s{4}\[(.+?)\] \=\> /m", $in, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
        $pos = array();
        $previous_key = '';
        $in_length = strlen($in);
        // store the following in $pos:
        // array with key = key of the parsed array's item
        // value = array(start position in $in, $end position in $in)
        foreach ($matches as $match) {
            $key = $match[1][0];
            $start = $match[0][1] + strlen($match[0][0]);
            $pos[$key] = array($start, $in_length);
            if ($previous_key != '') $pos[$previous_key][1] = $match[0][1] - 1;
            $previous_key = $key;
        }
        $ret = array();
        foreach ($pos as $key => $where) {
            // recursively see if the parsed out value is an array too
            $ret[$key] = print_r_reverse(substr($in, $where[0], $where[1] - $where[0]));
        }
        return $ret;
    }
}

?>

 

Hopefully that function helps you out. It would take the whole first section of code as the string.

Sure, or maybe I can use preg_spilt(), but I thought there may be an easier way to convert it directly. Change the datatype somehow or something else. BTW, I tried changing the datatype, but that wasn't as easy as I thought.

 

If you have syntax correct code you can use eval but that being used in the wrong way can open up security holes in your server (And many hosts have it disabled because of that). An example:

 

$array_string =  "\$array_from_string = array(0 => 'Rakel', 1 => 'Dix', 
2 => array(0 => 'Barne', 1 => 'Barn'), 
3 => array(0 => 'Tisse', 1 => 'Mann'), 
4 => 'Julenissen', 5 => 'Nisse', 6 => 'Far');";

// be cautious with the eval function. 
eval($array_string);

 

Would make that into a valid array. (note I had to modify the string to be formed with correct syntax etc.

Sure, or maybe I can use preg_spilt(), but I thought there may be an easier way to convert it directly. Change the datatype somehow or something else. BTW, I tried changing the datatype, but that wasn't as easy as I thought.

 

If you have syntax correct code you can use eval but that being used in the wrong way can open up security holes in your server (And many hosts have it disabled because of that). An example:

 

$array_string =  "\$array_from_string = array(0 => 'Rakel', 1 => 'Dix', 
2 => array(0 => 'Barne', 1 => 'Barn'), 
3 => array(0 => 'Tisse', 1 => 'Mann'), 
4 => 'Julenissen', 5 => 'Nisse', 6 => 'Far');";

// be cautious with the eval function. 
eval($array_string);

 

Would make that into a valid array. (note I had to modify the string to be formed with correct syntax etc.

 

Great!

 

It works on my sever! I will be careful with it!M

Ladies and Gents, here is a function that you can use to transform an array containing any keys and values that may be string, int og array to a string, that can be converted back again using eval(). This without losing the datatype

 

This is useful if you need to multi-dimentional arrays across from scripts as strings and decode them:

 

<?php

//FUNCTION THAT CONVERTS ARRAY2STRING. 
//$array is the array to be converted.
//$string_variable_name is a string with the name of the array once the string is converted from string back to array again.

function array2str($array, $string_variable_name = 'decoded_array') {
$str = '$' . $string_variable_name . ' = array(';
//IF string
function str($key, $value) {
	if (is_string($key)) {
		$key = "'$key'";
	}
	$str2 = "$key => '$value', ";
	return $str2;
}
//IF int
function inte($key, $value) {
	if (is_string($key)) {
		$key = "'$key'";
	}
	$str2 = "$key => $value, ";
	return $str2;
}
//IF array
function arry($key, $value) {
	if (is_string($key)) {
		$key = "'$key'";
	}
	$str1 = "$key => array(";
	foreach ($value as $key1 => $value1) {
		if (is_string($value1) || is_int($value1) ) {
			$str1 .= str($key1, $value1);
		}
		elseif (is_array($value1)) {
			$str1 .= arry($key1, $value1);
		}
	}
	$str1 .= '),';
	return $str1;
}
foreach ($array as $key => $value) {
	if (is_string($value) ) {
		$str .= str($key, $value);
	}
	elseif (is_int($value)) {
		$str .= inte($key, $value);
	}
	elseif (is_array($value)) {
		$str .= arry($key, $value);
	}
}
$str .= ');';
return $str;	
}

//OUR TEST ARRAY
$info[0] = 'Rakel';
$info['s'] = 1;
$info[2][0] = 'Barne';
$info[2][1] = 'Barn';
$info[2][2][0] = 'Tisse';
$info[2][2][1] = 'Mann';
$info[2][2][2][1] = 'Marius';
$info[2][2][2][2] = 'Jonsson';
$info[2][3] = '1';
$info['Rakel'] = 2;
$info[4] = 'Far';

//PRINT OUR TEST ARRAY
print 'Original array:<pre>';
print_r($info);
print '</pre>';
/*PRINTS:

Array
(
    [0] => Rakel
    [s] => 1
    [2] => Array
        (
            [0] => Barne
            [1] => Barn
            [2] => Array
                (
                    [0] => Tisse
                    [1] => Mann
                    [2] => Array
                        (
                            [1] => Marius
                            [2] => Jonsson
                        )

                )

            [3] => 1
        )

    [Rakel] => 2
    [4] => Far
)

*/

//CONVERT TO STRING
$new_string = array2str($info);
print $new_string;
//OUTPUTS: $decoded_array = array(0 => 'Rakel', 's' => 1, 2 => array(0 => 'Barne', 1 => 'Barn', 2 => array(0 => 'Tisse', 1 => 'Mann', 2 => array(1 => 'Marius', 2 => 'Jonsson', ),),3 => '1', ),'Rakel' => 2, 4 => 'Far', );


//DECODE STRING TO ARRAY
eval($new_string);
print_r($decoded_array);
/*PRINTS:

Array
(
    [0] => Rakel
    [s] => 1
    [2] => Array
        (
            [0] => Barne
            [1] => Barn
            [2] => Array
                (
                    [0] => Tisse
                    [1] => Mann
                    [2] => Array
                        (
                            [1] => Marius
                            [2] => Jonsson
                        )

                )

            [3] => 1
        )

    [Rakel] => 2
    [4] => Far
)

*/
?>

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.