How to export PHP array where each key-value pair is in separate line?

China☆狼群 提交于 2019-12-05 19:47:14

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!