[英]Output PHP array as PHP code, formatted
I have a file with a HUGE array that goes multiple dimensions deep and looks a bit like this.我有一个包含 HUGE 数组的文件,该数组具有多个维度,看起来有点像这样。
$array = array(
'all_tools' => array(
'title' => 'Tools',
'help' => 'Help with tools'
),
'addcode' => array(
'title' => 'Add Code',
'help' => 'Add code help'
),
'editcode' => array(
'title' => 'Edit Code',
'help' => 'Edit code help'
)
);
Apparently this is not readable enough and I've been asked to convert this array to the following format.显然这不够可读,我被要求将此数组转换为以下格式。
$array['all_tools']['title'] = 'Tools';
$array['all_tools']['help'] = 'Help with tools';
$array['addcode']['title'] = 'Add Code';
$array['addcode']['help'] = 'Add code help';
$array['editcode']['title'] = 'Edit Code';
$array['editcode']['help'] = 'Edit code help';
It is the same array, but I need to structure it like this.它是同一个数组,但我需要像这样构造它。 This will take hours to do by hand because this file is enormous.
这需要几个小时才能手工完成,因为这个文件很大。 Does anyone know of a PHP function that will print the contents of a multi-dimensional array the way this way?
有谁知道以这种方式打印多维数组内容的 PHP 函数?
Edit: I would like a little more information.编辑:我想了解更多信息。 The array I am working on has some variation in how many arrays may be nested in each key.
我正在处理的数组在每个键中可以嵌套多少个数组有一些变化。 I need a solution that can go as many levels deep as necessary and dynamically knows when to stop when it bumps into a string rather than an array.
我需要一个解决方案,它可以根据需要深入到尽可能多的级别,并且当它碰到字符串而不是数组时动态知道何时停止。
This will spit out a text file you can copy and paste into your code:这将输出一个文本文件,您可以将其复制并粘贴到您的代码中:
foreach($array as $first_level_key => $value){
foreach($value as $sub_key => $sub_value){
echo "\$array['".$first_level_key."']['".$sub_key."'] = '$sub_value'; \n";
}
}
from the php.net manual for var_export来自var_export的 php.net 手册
<?php
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;
}
?>
If your output is to a text file and not an HTML page, remove the <br>s.
如果您的输出是文本文件而不是 HTML 页面,请删除 <br>s。
There are various ways you can output the PHP variable as directly consumable code.您可以通过多种方式将 PHP 变量输出为可直接使用的代码。
var_export
Just like var_dump
/ print_r
, you can use var_export
to just output the array as consumable(parsable) php code. var_export
就像var_dump
/ print_r
一样,您可以使用var_export
将数组输出为可消耗(可解析)的 php 代码。
json_encode
you can output the array to JSON
encoded format, which will be consumable by not only the PHP
language, but also most of the other language since JSON
is a language agnostic format. json_encode
您可以将数组输出为JSON
编码格式,这不仅适用于PHP
语言,而且适用于大多数其他语言,因为JSON
是一种与语言无关的格式。
Use your own function/method to generate the output php
string.使用您自己的函数/方法来生成输出
php
字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.