I'm trying to 'pretty-print' out an array, using a syntax like:
我试图使用如下语法'漂亮'打印出一个数组:
$outString = "[";
foreach($arr as $key=>$value) {
// Do stuff with the key + value, putting the result in $outString.
$outString .= ", ";
}
$outString .= "]";
However the obvious downside of this method is that it will show a "," at the end of the array print out, before the closing "]". Is there a good way using the $key=>$value syntax to detect if you're on the last pair in the array, or should I switch to a loop using each()
instead?
然而,这种方法的明显缺点是它会在数组打印结束时,在结束“]之前显示”,“。是否有一种很好的方法使用$ key => $ value语法来检测你是否在数组中的最后一对,或者我应该使用each()来切换到循环?
8 个解决方案
#1
12
Build up an array, and then use implode
:
构建一个数组,然后使用implode:
$parts = array();
foreach($arr as $key=>$value) {
$parts[] = process($key, $value);
}
$outString = "[". implode(", ", $parts) . "]";
#2
4
You can just trim off the last ", " when for terminates by using substring.
您可以通过使用子字符串来修剪最后一个“,”。
$outString = "[";
foreach($arr as $key=>$value) {
// Do stuff with the key + value, putting the result in $outString.
$outString .= ", ";
}
$outString = substr($outString,-2)."]"; //trim off last ", "
#3
4
Do the processing separately and then use implode()
to join:
单独进行处理,然后使用implode()加入:
$outArr = array();
foreach($arr as $key => $value) {
$outArr[] = process($key, $value);
}
$outString = '[' . implode(', ', $outArr) . ']';
#4
3
Notwithstanding the circumstances of your example (joining strings with commas, for which implode is the right way to go about it), to answer your specific question, the canonical way to iterate through an array and check if you're on the last element is using CachingIterator:
尽管您的示例的情况(用逗号连接字符串,其中内容是正确的方式),回答您的具体问题,迭代数组并检查您是否在最后一个元素的规范方法是使用CachingIterator:
<?php
$array = array('k'=>'v', 'k1'=>'v1');
$iter = new CachingIterator(new ArrayIterator($array));
$out = '';
foreach ($iter as $key=>$value) {
$out .= $value;
// CachingIterator->hasNext() tells you if there is another
// value after the current one.
if ($iter->hasNext()) {
$out .= ', ';
}
}
echo $out;
#5
2
It might be easier to do it like this, and add a comma to the string before the item if it isn't the first item.
这样做可能更容易,如果它不是第一个项目,则在项目之前为字符串添加逗号。
$first= true;
foreach ($arr as $key => $value) {
if (! $first) {
$outString .=', ';
} else {
$first = false;
}
//add stuff to $outString
}
Is the output format JSON? If so you could consider using json_encode()
instead.
输出格式是JSON吗?如果是这样,你可以考虑使用json_encode()。
#6
1
You could do it as a normal for loop:
您可以将其作为正常的循环:
$outString = "[";
for ($i = 0; $i < count($arr); $i++) {
// Do stuff
if ($i != count($arr) - 1) {
$outString += ", ";
}
}
However, the nicest way to do it, IMHO, is storing all the components in an array, and then imploding:
但是,最好的方法,恕我直言,将所有组件存储在一个数组中,然后插入:
$outString = '[' . implode(', ', $arr) . ']';
implode() takes all elements in an array and puts them together in a string, separated by its first argument.
implode()获取数组中的所有元素,并将它们放在一个字符串中,由第一个参数分隔。
#7
1
There are many possibilities. I think this is one of the simplest solutions:
有很多种可能性。我认为这是最简单的解决方案之一:
$arr = array(0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd', 4 => 'e', 5 => 'f', 6 => 'g');
echo '[', current($arr);
while ($n = next($arr)) echo ',', $n;
echo ']';
Outputs:
输出:
[a,b,c,d,e,f,g]
#8
1
I tend to avoid using loops in situations such as these. You should use implode() to join lists with a common deliminator and use array_map() to handle any processing on that array before the join. Note the following implementations that should express the versatility of these functions. Array map can take a string (name of a function) representing either a built-in function or user defined function (first 3 examples). You may pass it a function using create_function() or pass a lambda/anonymous function as the first parameter.
我倾向于避免在诸如此类的情况下使用循环。您应该使用implode()来连接具有公共分隔符的列表,并使用array_map()在连接之前处理该数组上的任何处理。请注意以下实现应表达这些功能的多功能性。数组映射可以采用表示内置函数或用户定义函数的字符串(函数名称)(前3个示例)。您可以使用create_function()传递一个函数,或者传递一个lambda / anonymous函数作为第一个参数。
$a = array(1, 2, 3, 4, 5);
// Using the user defined function
function fn ($n) { return $n * $n; }
printf('[%s]', implode(', ', array_map('fn', $a)));
// Outputs: [1, 4, 9, 16, 25]
// Using built in htmlentities (passing additional parameter
printf('[%s]', implode(', ', array_map( 'intval' , $a)));
// Outputs: [1, 2, 3, 4, 5]
// Using built in htmlentities (passing additional parameter
$b = array('"php"', '"&<>');
printf('[%s]', implode(', ', array_map( 'htmlentities' , $b, array_fill(0 , count($b) , ENT_QUOTES) )));
// Outputs: ["php", "&<>]
// Using create_function <PHP 5
printf('[%s]', implode(', ', array_map(create_function('$n', 'return $n + $n;'), $a)));
// Outputs: [2, 4, 6, 8, 10]
// Using a lambda function (PHP 5.3.0+)
printf('[%s]', implode(', ', array_map(function($n) { return $n; }, $a)));
// Outputs: [1, 2, 3, 4, 5]
#1
12
Build up an array, and then use implode
:
构建一个数组,然后使用implode:
$parts = array();
foreach($arr as $key=>$value) {
$parts[] = process($key, $value);
}
$outString = "[". implode(", ", $parts) . "]";
#2
4
You can just trim off the last ", " when for terminates by using substring.
您可以通过使用子字符串来修剪最后一个“,”。
$outString = "[";
foreach($arr as $key=>$value) {
// Do stuff with the key + value, putting the result in $outString.
$outString .= ", ";
}
$outString = substr($outString,-2)."]"; //trim off last ", "
#3
4
Do the processing separately and then use implode()
to join:
单独进行处理,然后使用implode()加入:
$outArr = array();
foreach($arr as $key => $value) {
$outArr[] = process($key, $value);
}
$outString = '[' . implode(', ', $outArr) . ']';
#4
3
Notwithstanding the circumstances of your example (joining strings with commas, for which implode is the right way to go about it), to answer your specific question, the canonical way to iterate through an array and check if you're on the last element is using CachingIterator:
尽管您的示例的情况(用逗号连接字符串,其中内容是正确的方式),回答您的具体问题,迭代数组并检查您是否在最后一个元素的规范方法是使用CachingIterator:
<?php
$array = array('k'=>'v', 'k1'=>'v1');
$iter = new CachingIterator(new ArrayIterator($array));
$out = '';
foreach ($iter as $key=>$value) {
$out .= $value;
// CachingIterator->hasNext() tells you if there is another
// value after the current one.
if ($iter->hasNext()) {
$out .= ', ';
}
}
echo $out;
#5
2
It might be easier to do it like this, and add a comma to the string before the item if it isn't the first item.
这样做可能更容易,如果它不是第一个项目,则在项目之前为字符串添加逗号。
$first= true;
foreach ($arr as $key => $value) {
if (! $first) {
$outString .=', ';
} else {
$first = false;
}
//add stuff to $outString
}
Is the output format JSON? If so you could consider using json_encode()
instead.
输出格式是JSON吗?如果是这样,你可以考虑使用json_encode()。
#6
1
You could do it as a normal for loop:
您可以将其作为正常的循环:
$outString = "[";
for ($i = 0; $i < count($arr); $i++) {
// Do stuff
if ($i != count($arr) - 1) {
$outString += ", ";
}
}
However, the nicest way to do it, IMHO, is storing all the components in an array, and then imploding:
但是,最好的方法,恕我直言,将所有组件存储在一个数组中,然后插入:
$outString = '[' . implode(', ', $arr) . ']';
implode() takes all elements in an array and puts them together in a string, separated by its first argument.
implode()获取数组中的所有元素,并将它们放在一个字符串中,由第一个参数分隔。
#7
1
There are many possibilities. I think this is one of the simplest solutions:
有很多种可能性。我认为这是最简单的解决方案之一:
$arr = array(0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd', 4 => 'e', 5 => 'f', 6 => 'g');
echo '[', current($arr);
while ($n = next($arr)) echo ',', $n;
echo ']';
Outputs:
输出:
[a,b,c,d,e,f,g]
#8
1
I tend to avoid using loops in situations such as these. You should use implode() to join lists with a common deliminator and use array_map() to handle any processing on that array before the join. Note the following implementations that should express the versatility of these functions. Array map can take a string (name of a function) representing either a built-in function or user defined function (first 3 examples). You may pass it a function using create_function() or pass a lambda/anonymous function as the first parameter.
我倾向于避免在诸如此类的情况下使用循环。您应该使用implode()来连接具有公共分隔符的列表,并使用array_map()在连接之前处理该数组上的任何处理。请注意以下实现应表达这些功能的多功能性。数组映射可以采用表示内置函数或用户定义函数的字符串(函数名称)(前3个示例)。您可以使用create_function()传递一个函数,或者传递一个lambda / anonymous函数作为第一个参数。
$a = array(1, 2, 3, 4, 5);
// Using the user defined function
function fn ($n) { return $n * $n; }
printf('[%s]', implode(', ', array_map('fn', $a)));
// Outputs: [1, 4, 9, 16, 25]
// Using built in htmlentities (passing additional parameter
printf('[%s]', implode(', ', array_map( 'intval' , $a)));
// Outputs: [1, 2, 3, 4, 5]
// Using built in htmlentities (passing additional parameter
$b = array('"php"', '"&<>');
printf('[%s]', implode(', ', array_map( 'htmlentities' , $b, array_fill(0 , count($b) , ENT_QUOTES) )));
// Outputs: ["php", "&<>]
// Using create_function <PHP 5
printf('[%s]', implode(', ', array_map(create_function('$n', 'return $n + $n;'), $a)));
// Outputs: [2, 4, 6, 8, 10]
// Using a lambda function (PHP 5.3.0+)
printf('[%s]', implode(', ', array_map(function($n) { return $n; }, $a)));
// Outputs: [1, 2, 3, 4, 5]