简体   繁体   English

PHP - 当使用foreach循环遍历数组时,我怎么能判断我是否在最后一对?

[英]PHP - when using foreach to loop through array, how can I tell if I'm on the last pair?

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()来切换到循环?

Build up an array, and then use implode : 构建一个数组,然后使用implode

$parts = array();
foreach($arr as $key=>$value) {
    $parts[] = process($key, $value);
}

$outString = "[". implode(", ", $parts) . "]";

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 ", "

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) . ']';

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;

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? 输出格式是JSON吗? If so you could consider using json_encode() instead. 如果是这样,你可以考虑使用json_encode()代替。

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()获取数组中的所有元素,并将它们放在一个字符串中,由第一个参数分隔。

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]

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. 您应该使用implode()来连接具有公共分隔符的列表,并使用array_map()在连接之前处理该数组上的任何处理。 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). 数组映射可以采用表示内置函数或用户定义函数的字符串(函数名称)(前3个示例)。 You may pass it a function using create_function() or pass a lambda/anonymous function as the first parameter. 您可以使用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: [&quot;php&quot;, &quot;&amp;&lt;&gt;]

// 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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用PHP中的foreach循环将$ key =&gt; $ value对添加到关联数组? - How can I add a $key=>$value pair to an associative array using a foreach loop in PHP? 如何不使用foreach遍历多维数组 - How can I loop through multidimensional array without using foreach 如何使用php按字母顺序对此数组进行排序,并使用foreach循环遍历它 - How can I sort this array alphabetically using php and use foreach to loop through it 如何使用 PHP foreach 循环(或不使用)重构关联数组? - how can I restructure an associative array using a PHP foreach loop (or not)? 我如何在 php 中循环这个数组 - How can I foreach loop this array in php 如何使用array_push在PHP / Laravel中通过数据库查询结果在foreach循环中添加键值对以标记返回的每一行? - How can I use array_push to add a key value pair in a foreach loop through database query results in PHP/Laravel to flag each row returned? 我如何遍历此数组-PHP - How can I loop through this array - PHP 使用 foreach 循环和引用时,如何停止最后一个成员指向引用? - When using a foreach loop and a reference, how can I stop the last member pointing to a reference? 如何使用PHP中的标准for循环打印排序数组? (不是foreach循环) - How can I print a sorted array using a standard for loop in PHP? (Not a foreach loop) 如何使用PHP中的foreach循环将数组的一个元素添加到另一个数组的所有元素 - How can I add one element of array to all elements of another array using foreach loop in php
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM