duanhuang4306 2014-11-26 19:28
浏览 58
已采纳

Laravel PHP:按字母顺序在下拉列表中显示数组元素,而不使用sort()

I have a Laravel PHP Photo Gallery application that allows the user to create an album and then insert photos into an album of their choice from a drop down list. This requires the user to create the album first since the drop down list is dynamic based on which albums actually exist. The drop down list is currently functioning properly but it does not display albums (array elements) alphabetically.

I've tried using the 'sort()' method but the problem is that the array element ids then become switched/re-sorted when doing so. I do not want the array ids to be re-sorted since this will put photos into the wrong albums.

So I want to know if there is a way to display the albums alphabetically in a drop down list while not re-sorting their array element ids.

Controller:

public function create()
{
    $stoneArray = $this->stone->all()->toArray();

    if (empty($stoneArray)) {
        $dropdown[0] = 'There are no stones';
    }

    foreach ($stoneArray as $stone) {
        $dropdown[$stone['stone_id']] = $stone['stone_name'];
        // sort($dropdown); /* This re-sorted the array element ids */

    }

    $data = array('type' => 'stone_photo', 'dropdown' => $dropdown);
    $this->layout->content = \View::make('forms.stones.new-photo', $data);
}

View:

<div class="form-group">
    {{ Form::label('stone_id', 'Stone: ') }}
    {{ Form::select('stone_id', $dropdown, array('class' => 'form-control')) }}
</div>

Any help is greatly appreciated! Thank you!

  • 写回答

1条回答 默认 最新

  • doujiao3998 2014-11-26 19:36
    关注

    EDIT

    I'm making some assumptions here about your file structure, but it should give you the idea.

    In: app\Acmeepositories\Eloquent\EloquentStoneRepository.php or whatever you called it, there's a function:

    public function all()
    {
      return Stone::all();
    }
    

    (I think that's what it looks like, but I'm not positive). Try changing that to:

    public function all()
    {
      return Stone::orderBy('column_name', 'asc')->get();
    }
    

    If you use all() somewhere else and don't want it sorted, consider adding another function:

    public function all_sorted()
    {
      return Stone::orderBy('column_name', 'asc')->get();
    }
    

    Hope that helps!

    Edit: Changed ->all() to ->get() so eloquent can properly sort it.

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

报告相同问题?

悬赏问题

  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题