Php 如何在一行上打印数组

Php 如何在一行上打印数组,php,html,arrays,Php,Html,Arrays,我一直在寻找答案,但没有一个答案与我的问题有直接的联系,或者我无法调整它来解决我的问题 如何在一行中打印以下内容 <?php $product_array = array("id"=>001, "description"=>"phones", "type"=>"iphone"); print "Print the product_array = "; print_r($product_array); ?> 当前结果 打印产品\u array=array

我一直在寻找答案,但没有一个答案与我的问题有直接的联系,或者我无法调整它来解决我的问题

如何在一行中打印以下内容

<?php

$product_array = array("id"=>001, "description"=>"phones", "type"=>"iphone");


print "Print the product_array = ";
print_r($product_array);

?>

当前结果

打印产品\u array=array

(

[id]=>001

[说明]=>手机

[输入]=>iphone

)

想要的结果

打印产品_array=array([id]=>001[description]=>phones) [输入]=>iphone)


print\u r的第二个值允许函数返回值,而不是直接打印出来。

如果您只是想查看数组的内容以进行监视或调试,那么将数组编码为JSON可能会很有用:

print "Print the product_array = " . json_encode($product_array);
结果:

打印产品_数组={“id”:1,“description”:“phones”,“type”:“iphone”}


或者,您可以使用获取变量的可解析表示形式,然后简单地删除字符串中的所有新行字符

var\u export
-输出或返回变量的可解析字符串表示形式

下面是一个简单的例子:

$str = var_export($product_array, true);
print "Print the product_array = " .  str_replace(PHP_EOL, '', $str);
这将准确地为您提供指定的结果:

打印产品阵列('id'=>1,'description'=>'phones','type'=>'iphone',)



我建议使用第一个选项,因为它需要更少的字符串“操作”-第二个选项开始执行替换,第一个选项只是立即提供可读的输出。

注意,可以同时替换多个不同的字符(例如换行符和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}

默认情况下,它应该在浏览器的一行中呈现。简单,并且不需要多行源代码,以便于更简洁的输出。肯定比公认的答案要好,后者似乎因为不得不使用
print\r
而被挂断。
print json_encode(compact(['width', 'height'])) . PHP_EOL;
{"width":369,"height":245}