【问题标题】:Get only last 2 array using Foreach loop [duplicate]使用 Foreach 循环仅获取最后 2 个数组 [重复]
【发布时间】:2013-01-08 01:06:46
【问题描述】:

可能重复:
PHP foreach() return only last 50 items

我只需要它的最后 2 条记录。 下面的代码返回所有记录。谢谢

<?php 
    foreach ($fields as $field) {
        $type = $field['s_type'];
        $label = $field['s_label'];
        $value = Attributes::newInstance()->getValue($item_id, $field['pk_i_id']);
        if ($type == 'checkbox') {
            if ($value == 'checked') $value = 'Yes';
            else $value = 'No';
        }
?>
        <tr>
            <td style='width: 150px;'><?php _e($label, pg); ?></td>
            <td style='width: 150px;'><?php _e($value, pg); ?></td>
        </tr>

<?php } ?>

【问题讨论】:

  • 抱歉 $fileds 来自如下函数 $fields = Attributes::newInstance()->getFields();

标签: php mysql arrays foreach


【解决方案1】:

您可以在迭代之前使用数组切片来管理字段。

$last_two = array_slice($fields, -2);

foreach($last_two as $field) { ... }

虽然如果这是此脚本中唯一要做的事情,我建议重写您的查询结构。

【讨论】:

    【解决方案2】:

    你可以使用带有-2作为第二个参数的array_slice吗?

    【讨论】:

    • 感谢 Hakre 的帮助,这是我正在寻找的那个 foreach (array_slice($fields, -2) as $field) {
    • @user1956624 不要使用它,除非你想在每次迭代中计算切片数组...
    • 我在右侧的相关问题列表中找到了重复项。只需稍微搜索一下,您就会更快地找到答案;) - 并且还可以看到 Austin 在他的回答中的提示,关于您应该以只得到最后两个返回的方式查询数据库。这就是数据库查询应该这样做的方式。
    猜你喜欢
    • 1970-01-01
    • 2017-08-19
    • 1970-01-01
    • 2013-01-30
    • 1970-01-01
    • 2013-07-18
    • 2017-04-25
    • 2019-10-22
    • 2021-01-01
    相关资源
    最近更新 更多