英文:
Print array in one line
问题
只需要修改程序以按照你需要的格式输出。不需要创建另一个程序。你可以使用以下的PHP代码来实现所需的格式:
$data = array(
2019 => 15.63,
2020 => 4.96,
2021 => 42.92
);
$output = '[';
foreach ($data as $key => $value) {
$output .= $key . ' => ' . $value . ', ';
}
$output = rtrim($output, ', '); // 移除最后一个逗号和空格
$output .= ']';
echo $output;
这段代码将会输出你所需的格式:
[2019 => 15.63, 2020 => 4.96, 2021 => 42.92]
英文:
I have a program that prints result as an array:
Array
(
[2019] => 15.63
[2020] => 4.96
[2021] => 42.92
)
But I need to print it in such form:
[2019 => 15.63, 2020 => 4.96, 2021 => 42.92]
How could it be done? Do I have to make another program for it? Or is there any easier way?
答案1
得分: 0
-
你有默认的
print_r()
输出。没有格式化此输出的选项,但你可以根据需要转换输出。 -
将数组转换为 JSON 并进行一些替换。你还可以进一步替换逗号后的引号和空格。
$array = [10 => 11.22, 20 => 22.33, 30 => 33.44];
echo str_replace([':', '{', '}'], ['=>', '[', ']'], json_encode($array));
["10"=>11.22,"20"=>22.33,"30"=>33.44]
- 但这并不是一个好选择。更好的方法是根据你的需求重构输出。
$format = function ($key, $value) {
return "$key => $value";
};
echo '[', join(', ', array_map($format, array_keys($array), $array)), ']';
[10 => 11.22, 20 => 22.33, 30 => 33.44]
英文:
-
You have the default
print_r()
output. There is no option for formatting this, but you can transform the output as needed. -
Convert the array to JSON and do some replacements. You can go further and replace the quotes and spaces after comma.
$array = [10 => 11.22, 20 => 22.33, 30 => 33.44];
echo str_replace([':', '{', '}'], ['=>', '[', ']'], json_encode($array));
["10"=>11.22,"20"=>22.33,"30"=>33.44]
- But that's not a good choice. Better is to reconstruct the output by the transforms of your needs.
$format = function ($key, $value) {
return "$key => $value";
};
echo '[', join(', ', array_map($format, array_keys($array), $array)), ']';
[10 => 11.22, 20 => 22.33, 30 => 33.44]
答案2
得分: 0
我的建议将非常具体,适用于您的扁平输入数组。您似乎希望获得var_export()
的输出,但不带有老式数组语法,也不带有多行格式。
以下代码将使用现代花括号语法,并将换行符替换为单个空格。我的代码片段不适用于多维数组,如果您的键或值包含换行符,它可能会出错。对于基本的关联数组,可以安全使用。
输出:
[10 => 11.22, 20 => 22.33, 30 => 33.44]
如果您需要重新格式化更复杂的数据集,那么这将变成一个不太琐碎的任务,可能需要考虑实现一个分词器。
英文:
My advice will be very specific to your flat input array. It seems that you would like the output from var_export ()
but without the old skool array syntax and without the multiline formatting.
The following will use modern brace syntax and replace the newlines with single spaces. My snippet is not designed for multidimensional arrays and can be broken if your keys or values contain newlines. For your basic associative array, it is safe to use.
Code: (Demo)
$array = [10 => 11.22, 20 => 22.33, 30 => 33.44];
echo preg_replace(
['/^array \(\s+/', '/,?\R?\)$/', '/$\R /m'],
['[', ']', ' '],
var_export($array, true)
);
Output:
[10 => 11.22, 20 => 22.33, 30 => 33.44]
If you require more complicated data sets to be reformatted, then this would become a far less trivial task that should consider implementing a tokenizer.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论