在foreach语句PHP中将显示限制为10

时间:2017-11-18 21:08:19

标签: php function for-loop foreach

我有一个API,显示了近100项交易,我想将其限制在10只。我已经尝试过

if($bitcointrades == 10) break

但那并没有奏效。我拉数据后是否运行for循环?我应该将函数分解为两部分而不是使用elseif来呈现$ trade?以下是我正在使用的内容:

<?php

require_once('bitcoin.class.php');

$data = new Bitcoin();


$type = $_GET['type'];

$currency = $_GET['currency'];

if($type == 'ticker') {

$bitcoinlive = $data->getPrice($currency);

echo '<h2>1 Bitcoin is currently worth <span class="bitvalue">' . 
number_format((float)$bitcoinlive['last'], 2) . ' <span class="upper">' 
. $currency . '</span></span></h2>';
echo ' <p><span><i class="icon-arrow-up-circle"></i> High: ' . 
number_format((float)$bitcoinlive['high'], 2) . '</span> <span><i 
class="icon-arrow-down-circle"></i> Low: ' . 
number_format((float)$bitcoinlive['low'], 2) . '</span>';

} elseif($type == 'trades') {

$bitcointrades = $data->getTrades($currency);

foreach($bitcointrades as $trade) {
if($trade['type'] == 'buy') {
$ttype = '<span class="green"><i class="icon-plus-circle"></i> Buy 
Order</span>';
} else {
$ttype = '<span class="blue"><i class="icon-circle-minus"></i> Sell 
Order</span>';
}
echo' <tr> <th scope="row">' . $ttype . '</th> <td>' . $trade['price'] 
. ' <span class="upper">' . $currency . '</span></td> <td>' . 
$trade['amount'] . '</td> <td>' . $data->timeAgo($trade['date']) . 
'</td> </tr>';

}

}

3 个答案:

答案 0 :(得分:2)

这是正常的if($bitcointrades == 10) break不起作用。

$bitcointrades应该是一个包含您定义为$trade的交易的数组。

您需要使用迭代器i,如下例所示:

<?php
$i = 0;

foreach($bitcointrades as $trade) {
    if($i==10)
        break;
    // your logic here
    $i++;
}

答案 1 :(得分:1)

这样做

$i = 0;
foreach ($bitcointrades as $trade) {
if ($trade['type'] == 'buy') {
    $ttype = '<span class="green"><i class="icon-plus-circle"></i> Buy Order</span>';
} else {
    $ttype = '<span class="blue"><i class="icon-circle-minus"></i> Sell Order</span>';
}
echo ' <tr> <th scope="row">' . $ttype . '</th> <td>' . $trade['price']
    . ' <span class="upper">' . $currency . '</span></td> <td>' .
    $trade['amount'] . '</td> <td>' . $data->timeAgo($trade['date']) .
    '</td> </tr>';
$i++;
if ($i == 10) {
    break;
}
}

答案 2 :(得分:0)

您可以使用break完成foreach执行,这样您就可以使用cnt并中断

  $my_cnt = 0;
  foreach($bitcointrades as $trade) {
    if ($my_cnt >= 10) {
       break;
    }
    if($trade['type'] == 'buy') {
      $ttype = '<span class="green"><i class="icon-plus-circle"></i> Buy 
      Order</span>';
    } else {
      $ttype = '<span class="blue"><i class="icon-circle-minus"></i> Sell 
      Order</span>';
    }
    $my_cnt++;
}