How to export PHP array where each key-value pair

2019-05-12 18:19发布

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.

3条回答
祖国的老花朵
2楼-- · 2019-05-12 18:34

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.

查看更多
ら.Afraid
3楼-- · 2019-05-12 18:37

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

查看更多
爷的心禁止访问
4楼-- · 2019-05-12 18:42

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';
查看更多
登录 后发表回答