Laravel数组键未保留

时间:2015-01-13 21:14:14

标签: php arrays laravel laravel-4

目前正在运行Laravel 4.1.31。在控制器中,数组由用户构建,其id为密钥:

$owners = User::get()->lists('username','id');

在控制器级别打印所有者阵列将产生以下结果:

print_r($owners)

// Array
// (
//    [1] => user1
//    [2] => user2
//    [4] => user3  <--- key jumps to 4, this is correct
//    [5] => user4
//    [6] => user5
// )

但是,一旦将数组传递给视图,则不保留键,在视图级别将其打印出来会产生以下结果:

// Array
// (
//    [1] => user1
//    [2] => user2
//    [3] => user3  <--- key was replaced with 3, this is incorrect
//    [4] => user4       all values from this point on are now shifted
//    [5] => user5
// )

原始数组中没有3个键但是一旦传递给视图,所有内容都会移动以填补空白。这最终导致问题,因为现在2以上的所有id都不匹配。如何保留数组键?

完全控制器方法:

public function edit($id) {

  // get the task
  $task = $this->task->find($id);

  // grab all users for owner field
  $owners = User::get()->lists('username','id');

  // grab all projects for project field
  $projects = Project::get()->lists('title','id');

  // add placeholder to beginning of arrays
  array_unshift($owners, 'Select Owner');
  array_unshift($projects, 'Select Project');

  // return show view
  return View::make('tasks.edit', array(
    'task'     => $task,
    'status'   => $this->status,
    'projects' => $projects,
    'owners'   => $owners
  )); 

}

2 个答案:

答案 0 :(得分:2)

array_unshift更改数组的键。它会将它们重置为数字序列0,1,2,3,...

使用此选项在数组的开头添加键""的值:

$owners = ['' => 'Select Owner'] + $owners;

答案 1 :(得分:2)

如评论中所述,摆脱两个阵列上的array_unshift。在视图中,按如下方式处理:

<select name="projects">
  <option value="">Select Project</option>
  @foreach($projects AS $project)
  <option value="{{ $project->id }}">{{ $project->title }}</option>
  @endforeach
</select>

不是将第一个元素设为通用值,而是在处理@foreach以进行选择之前对其进行硬编码

希望有所帮助!