如何在一行中打印以下内容?
$product_array = array(
"id" => 001,
"description" => "phones",
"type" => "iphone"
);
print "Print the product_array = ";
print_r($product_array);
当前结果
Print the product_array =Array
(
[id] => 001
[description] => phones
[type] => iphone
)
想要的结果
Print the product_array =Array ( [id] => 001 [description] => phones [type] => iphone )
如果您只是为了监视或调试目的而查看数组的内容,也许将数组编码为 JSON 会很有用:
print "Print the product_array = " . json_encode($product_array);
结果:
打印product_array = {"id":1,"description":"phones","type":"iphone"}
var_export
函数 获取变量的可解析表示形式,然后简单地删除字符串中的所有新行字符。
— 输出或返回变量的可解析字符串表示形式var_export
这是一个简单的例子:
$str = var_export($product_array, true);
print "Print the product_array = " . str_replace(PHP_EOL, '', $str);
这将为您提供您指定的准确结果:
打印 Product_array = array ( 'id' => 1, 'description' => 'phones', 'type' => 'iphone',)
我会推荐第一个选项,因为它需要较少的字符串“操作” - 第二个选项开始执行替换,而第一个选项只是立即提供可读的输出。
$arrayString = print_r($array, true);
echo str_replace("\n", "", $arrayString);
print_r 的第二个值让函数返回该值,而不是直接打印出来。
echo str_replace("\n", '', print_r($product_array, true));
请注意,可以同时替换多个不同的字符(例如换行符和 null),例如:
echo str_replace(array("\n", "\0"), "", print_r($product_array, 1))
这就是我用的:
$width = 150;
$height = 100;
print json_encode(compact('width')) . PHP_EOL;
print json_encode(compact('height')) . PHP_EOL;
输出为:
{"width":369}
{"height":245}
额外的好处是您可以一次将多个变量放入紧凑函数中:
print json_encode(compact(['width', 'height'])) . PHP_EOL;
本例的输出是:
{"width":369,"height":245}
刚刚添加了一些样式:
echo ltrim(rtrim(str_replace(["\n",'Array(', "[", "]", " => "], ['','', " / <span style='color: #0060df'>", "</span>", ": "], print_r($2d_array, true)), ")"), "/ ")