Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 带有var_转储数组输出的缩进_Php_String Formatting_Var Dump - Fatal编程技术网

Php 带有var_转储数组输出的缩进

Php 带有var_转储数组输出的缩进,php,string-formatting,var-dump,Php,String Formatting,Var Dump,我正在自动生成一些代码,并使用var_export以可解析的格式输出数组。关于如何使其缩进以便与输出的其余部分匹配,有什么想法吗 protected function getCode(){ $rs = ' $this->add('; $rs .= var_export($this->getArray(),true); $rs .= ');'.PHP_EOL; return $rs; } 我得到的输出是 $th

我正在自动生成一些代码,并使用var_export以可解析的格式输出数组。关于如何使其缩进以便与输出的其余部分匹配,有什么想法吗

protected function getCode(){
    $rs = '            $this->add(';
    $rs .= var_export($this->getArray(),true);
    $rs .= ');'.PHP_EOL;
    return $rs;
}
我得到的输出是

          $this->add(array (
  'name' => 'notes',
  'attributes' => 
  array (
    'label' => 'Date',
    'label_attributes' => 
    array (
      'class' => 'col-md-4 control-label',
    ),
  ),
));
我希望它有正确的空格

          $this->add(array (
                       'name' => 'notes',
                       'attributes' => 
                       array (
                         'label' => 'Date',
                         'label_attributes' => 
                         array (
                           'class' => 'col-md-4 control-label',
                         ),
                       ),
                     ));

不能定义
var\u dump()
var\u export()
放入文本中的空白

更好的选择是编写一个函数,以您想要的格式打印数组的详细信息。或者,您可以更改打印文本后解析文本的方式,以解析
var\u dump()
var\u export()提供给您的内容

编辑:

我的错,我想到了另一种方法,你可以做到这一点。它需要使用
str\u replace()
var\u dump()
使用
\n
进行格式化来吐出变量,因此您可以执行以下操作:

echo str\u replace(“,”this->getArray())


您必须确定要用什么替换
,以获得所需的格式,当然,这将设计用于HTML页面。这不是最容易做的事情(或者说是最漂亮的),但是如果你不想编写自己的函数来打印数组,那么至少可以尝试一下

这很难,会耗费你很多精力。 我认为您可以使用这种方式获得更好的格式:

function getCode(){
    $rs = '$data = ';
    $rs .= var_export($this->getArray() ,true) . ';' . PHP_EOL;
    $rs .= '$this->add($data);' . PHP_EOL;
    return $rs;
}
echo getCode($data);
输出将是:

$data = array (
  'name' => 'notes',
  'attributes' => 
  array (
    'label' => 'Date',
    'label_attributes' => 
    array (
      'class' => 'col-md-4 control-label',
    ),
  ),
);
$this->add($data);

使用
preg\u replace
这非常简单:

$array = array(
    array(
        "id" => 1,
        "foo" => "bar",
    ),
    array(
        "id" => 2,
        "foo" => "baz",
    ),
);

$str = var_export($array, true);
$str = preg_replace("/^/m", "    ", $str);
echo "    Indent:\n";
echo $str;

谢谢这起作用了。我添加了两个preg_replace来整理第一行和最后一行$rawString=preg_replace(“/^[$]/m”、“$”、$rawString)$rawString=preg_replace(“/^[);]”{3}/m“,”);”$原始字符串)