修改数组的第一项

时间:2016-02-08 15:40:28

标签: php arrays codeigniter

我必须修改数组的第一项,但是我失败了,但我设法做了一个代码:

<div class="carousel-inner">                        
    <?php if($results) {
        $x= 1;
        foreach ($results as $data)  { $x++; ?>
            <div class="item <?php if($x == 1) { echo 'active';} ?>">
                <img alt="" src="<?=base_url('uploads/'.$data->file)?>">
            </div>
        <?php }
    } ?>                        
</div>

假设我会得到这些结果:

<div class="item active">
    <img alt="" src="http://localhost/ideal_visa/uploads/fd5fa6cfbe64c8b68664ddbf0546d81b.jpg">
</div>
<div class="item">
    <img alt="" src="http://localhost/ideal_visa/uploads/c43c064de5cb9e751c723eb9791f2107.jpg">
</div>
<div class="item">
    <img alt="" src="http://localhost/ideal_visa/uploads/e3137475f6330d52e9cd9c6fc5efba1e.jpg">
</div>

我只需要在数组的第一项上添加active

4 个答案:

答案 0 :(得分:0)

<div class="carousel-inner">                        
    <?php if($results) {
        $x= 1;
        foreach ($results as $data)  { ?>
            <div class="item <?php if($x == 1) { echo 'active';} ?>">
                <img alt="" src="<?=base_url('uploads/'.$data->file)?>">
            </div>
        <?php  $x++; }
    } ?>                        
</div>

您需要在迭代后增加x

<div class="carousel-inner">                        
        <?php if($results) {
            foreach ($results as $x=>$data)  { ?>
                <div class="item <?php if($x==0) echo 'active'; ?>">
                    <img alt="" src="<?=base_url('uploads/'.$data->file)?>">
                </div>
            <?php }
        } ?>                        
    </div>

您可以使用数组$data的关联键并将条件更改为$x==0

答案 1 :(得分:0)

您无需为此执行额外的$x。您可以将foreachkey => value一起使用,并检查它是否是第一个索引

<?php if($results) {
    foreach ($results as $key=>$data)  { ?>
        <div class="item <?php echo ($key == 0)? 'active':''; ?>">
            <img alt="" src="<?=base_url('uploads/'.$data->file)?>">
        </div>
  <?php }
} ?> 

答案 2 :(得分:0)

问题

您已将$x=1放在foreach之前,然后在开始时将其增加

这意味着当您显示第一个图像时,$x==2

解决方案

您可以从$x=0 开始,也可以将行$x++移到循环的末尾:

    foreach ($results as $data)  { ?>
        <div class="item <?php if($x == 1) { echo 'active';} ?>">
            <img alt="" src="<?=base_url('uploads/'.$data->file)?>">
        </div>
    <?php $x++; }

答案 3 :(得分:0)

您需要在迭代

之后增加<?php if($results) { $x= 1; foreach ($results as $data) {?> <div class="item <?php if($x == 1) { echo 'active';} ?>"> <img alt="" src="<?=base_url('uploads/'.$data->file)?>"> </div> <?php $x++; } } ?>
from collections import defaultdict
import datetime

# list of columns returned from your database query
columns = ["city", "state", "index", "phone", "art", "exp-date", "arrival-date"]
usercheck = defaultdict(list)
for row in cur.fetchall():
    usercheck[row[0]] = defaultdict(list, zip(columns, row[1:]))

print usercheck