duanshan7261 2018-08-14 15:47
浏览 128
已采纳

声明使用PHP显示foreach输出的顺序

I am currently trying to set up a custom sortable list. Without getting into too much detail as this would become a very large post, I would like to use the PHP foreach function to show the list.

I currently have

$video_id = $row['videos'];
  $res = preg_replace("/[^0-9,.]/", "",$video_id);
$exclude = explode(',', $res);
} ?>

....

<ul id="sortable2" class="connectedSortable">
<?php foreach ($video_list as $key => $item): ?>
<?php if(in_array($item['id'], $exclude)){ ?>
<li id="video-<?php echo $item['id'] ?>"><?php echo $item['id'], 
$item['title'] ?></li>
<?php } ?>
<?php endforeach; ?>
</ul>

This generates a list of items from the database excluding items with an ID from an array which is also fetched from another table.

Screenshot of database

Screenshot of ID's to be excluded.

In this example, it will only show videos with the id 3,4 and 2. This is all working as expected. My issue is once I have reordered the items and refreshed the page they are loaded in numerical order. I need these to be load in the order specified (3,4 and 2 for this example).

Any help would be highly appreciated.

Thanks

  • 写回答

1条回答 默认 最新

  • douruduan8812 2018-08-14 16:00
    关注

    I think what you are looking for is ORDER BY FIELD (MySql), this lets you order by a field in a specific way.

    I need these to be load in the order specified (3,4 and 2 for this example).

    Sounds like a good fit to me!

    For example

       SELECT * FROM table WHERE id IN(3,4,2) ORDER BY FIELD(id, 3,4,2)
    

    This will select rows from table where the id is in the list and then order the results by id in the order they are place there, 3 then 4 then 2.

    excluding items with an ID

    This might cause some issue, the Field order by assumes you know at least some of the values in the field. Excluding implies that you know what you don't want but not necessarily what you do want, if that makes sense.

    Maybe it's not an issue, I don't have enough information on your particular use case to determine that, so I am just mentioning it as a cautionary thing.

    Thanks!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘