Recreate Original PHP Array from Print_R Output

Recreate original PHP array from print_r output

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

not my code, found here in the comments: print_r
'Matt' is the owner

How create an array from the output of an array printed with print_r?

I actually wrote a function that parses a "stringed array" into an actual array. Obviously, it's somewhat hacky and whatnot, but it works on my testcase. Here's a link to a functioning prototype at http://codepad.org/idlXdij3.

I'll post the code inline too, for those people that don't feel like clicking on the link:

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

}
?>

Create variable from print_r output

Amusingly the PHP manual contains an example that tries to recreate the original structure from the print_r output:

print_r_reverse()
http://www.php.net/manual/en/function.print-r.php#93529

However it does depend on whitespace being preserved. So you would need the actual HTML content, not the rendered text to pipe it back in.

Also it doesn't look like it could understand anything but arrays, and does not descend. That would be incredibly difficult as there is no real termination marker for strings, which can both contain newlines and ) or even [0] and => which could be mistaken for print_r delimiters. Correctly reparsing the print_r structure would be near impossible even with a recursive regex (and an actual parser) - it could only be accomplished by guesswork splitting like in the code linked above.. (There are two more versions there, maybe you have to try them through to find a match for your specific case.)

How do I convert a text file with a list of arrays into actual arrays in PHP

I am sure regex on each line could have been a better solution but for the sake of using explode and assuming contents of file are in $file

$lines = explode("\n",$file);
foreach($lines as &$line){
$line = explode("'",$line);
$output[$line[1]][0] = $line[3];
$output[$line[1]][1] = $line[5];
}
unset($lines);
var_dump($output);

Processing array to regenerate new array

I think that you a little bit complicate your code. You can access directly
$output['options']['data'] and it let you remove two outer loops.

$results = array();
foreach ($output['options']['data'] as $data) {
if (isset($data['labelValues'][0])) {
$results[$data['labelName']] = $data['labelValues'][0];
}
}

Note: I simplified accessing labelValues, because it looks form your example array, that there is always only one item. In other case, you should use your inner loop to iterate over all labelValues and concatenate them into one string perhaps.

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

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.

How do you reindex an array in PHP but with indexes starting from 1?

If you want to re-index starting to zero, simply do the following:

$iZero = array_values($arr);

If you need it to start at one, then use the following:

$iOne = array_combine(range(1, count($arr)), array_values($arr));

Here are the manual pages for the functions used:

  • array_values()
  • array_combine()
  • range()


Related Topics



Leave a reply



Submit