I'm looking for equivalent functionality to var_export()
which allows me to export PHP array into parseable code, but each statement should be printed in separate line (so each line has its own independent structure).
Currently this code:
<?php
$a = array (1, 2, array ("a", "b", "c"));
var_export($a);
?>
will output:
array (
0 => 1,
1 => 2,
2 =>
array (
0 => 'a',
1 => 'b',
2 => 'c',
),
)
However I'm looking to output into the following format like:
$foo = array()
$foo['0'] = 1
$foo['1'] = 2
$foo['2'] = array();
$foo['2']['0'] = 'a';
$foo['2']['1'] = 'b';
$foo['2']['2'] = 'c';
so execution of it will result in the same original array.
The goal is to manage very large arrays in human understandable format, so you can easily unset some selected items just by copy & paste method (where each line includes the full path to the element). Normally when you dump very big array on the screen, the problem is that you've to keep scrolling up very long time to find its parent's parent and it's almost impossible to find out which element belongs to which and what is their full path without wasting much amount of time.
Currently I've found here (posted by ravenswd) this simple function which can achieve that:
function recursive_print ($varname, $varval) {
if (! is_array($varval)):
print $varname . ' = ' . var_export($varval, true) . ";<br>\n";
else:
print $varname . " = array();<br>\n";
foreach ($varval as $key => $val):
recursive_print ($varname . "[" . var_export($key, true) . "]", $val);
endforeach;
endif;
}
Output for recursive_print('$a', $a);
:
$a = array();
$a[0] = 1;
$a[1] = 2;
$a[2] = array();
$a[2][0] = 'a';
$a[2][1] = 'b';
$a[2][2] = 'c';
You can go for a simple solution using json_encode
as follows.
<?php
$arrayA = array (1, 2, array ("a", "b", "c"));
$arrayString=json_encode($a);
$arrayB=json_decode($arrayString);
?>
Here, all you have to do is, encode the array into json (which will return an string) using json_encode
. Then, you can store the resulting string in anywhere you want.
When you read that string back, you have to call json_decode
in order to obtain the original php array.
Hope this is a simple solution to what you want to achieve.
Try this approach:
<?php
$sweet = array('a' => 'apple', 'b' => 'banana');
$fruits = array('sweet' => $sweet, 'sour' => 'lemon');
function print_item($item, $key){
echo "$key contains $item\n";
}
array_walk_recursive($fruits, 'print_item');
?>
The array walk recursive function, applies whatever function to all the elements in an array.
Cheers!
-Orallo
来源:https://stackoverflow.com/questions/37303504/how-to-export-php-array-where-each-key-value-pair-is-in-separate-line