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 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)