从条件 foreach 循环中获取第一个和最后一个数据



你好,我遇到了一个奇怪的问题,我想要来自for-each 循环的第一个数据和最后一个数据。 为此,我已经看到了这个答案。 这将非常有帮助,但在这里我的情况真的有点复杂。 我有如下循环

<?php
$count = 0;
$length = count($myDataArray);
foreach ($myDataArray as $value) {
if($count >= 7)
{
//Some Data to Print
//this is first data for me
<tr >
<td><?=$myfinaldate?></td>
<td><?=$stockdata[1]?></td>
<td><?=$stockdata[2]?></td>
<td><?=$stockdata[3]?></td>
<td <?php if($count == 8)echo "style='background-color:#47ff77;'"; ?>><?=$stockdata[4]?></td>
<td><?=$stockdata[5]?></td>
<td><?php echo $mydate; ?></td>
</tr>
<?php
}
$count++;
}

现在如何从循环中获取第一个和最后一个数据?

我想你可以使用你的length属性。 当您拥有数组的总数时,只需检查myDataArray[0]myDataArray[$length-1]

要获取数组的第一个和最后一个值,请使用以下函数:

$array = $myDataArray;
$array_values = array_values($myDataArray);
// get the first value in the array
print $array_values[0]; // prints 'first item'
// get the last value in the array
print $array_values[count($array_values) - 1]; // prints 'last item'

您可以使用array_values删除数组的键并将它们替换为索引。如果执行此操作,则可以直接访问指定的字段。像这样,您可以检查对数组的要求,而无需循环访问它,如下面的if-条件所示:

$length = count($myDataArray);
$dataArrayValues = array_values($myDataArray);
$wantedFields = [];
if ($length >= 8) {
$wantedFields[] = $dataArrayValues[7];
if ($length > 8) {
$wantedFields[] = end($dataArrayValues);
}
}

由于条件,如果它也是最后一个字段,您将不会打印第 8 个字段两次。

foreach ($wantedFields as $value) {
<tr>
... //Your previous code
</tr>
}

相关内容

最新更新