使用正确的语法将 PHP 数组打印成字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7316798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:28:07  来源:igfitidea点击:

Printing PHP Array into a string with correct syntax

phparrays

提问by Aivan Monceller

If I have this array:

如果我有这个数组:

<?php 

$myarray =  Array
                (
                        'keyword' => 'seo',
                        'title_factor' => false,
                        'description_factor' => false,
                        'headtags_factor' => false,
                        'imgalt_factor' => false,
                        'keyword_density' => 0,
                );


var_dump($myarray);
print_r($myarray);                      


?>

Here is the output of vardump and print_r:

这是 vardump 和 print_r 的输出:

array(6) {
  ["keyword"]=>
  string(3) "seo"
  ["title_factor"]=>
  bool(false)
  ["description_factor"]=>
  bool(false)
  ["headtags_factor"]=>
  bool(false)
  ["imgalt_factor"]=>
  bool(false)
  ["keyword_density"]=>
  int(0)
}
Array
(
    [keyword] => 'seo'
    [title_factor] => 
    [description_factor] => 
    [headtags_factor] => 
    [imgalt_factor] => 
    [keyword_density] => 0
)

Here is what I want as output:

这是我想要的输出:

    "Array
    (
            'keyword' => 'seo',
            'title_factor' => false,
            'description_factor' => false,
            'headtags_factor' => false,
            'imgalt_factor' => false,
            'keyword_density' => 0,
    );"    

回答by Arnaud Le Blanc

Use var_export()[docs]:

使用var_export()[文档]

$string = var_export($array, true);

回答by Tom Vervoort

You're searching for var_exportif I'm correct

你在寻找var_export我是否正确

more info about var_export at http://www.php.net/manual/en/function.var-export.php

有关 var_export 的更多信息,请访问http://www.php.net/manual/en/function.var-export.php