Pluck id(整数)转换为字符串 Laravel

Pluck id (integer) cast to string Laravel

从数据库中提取时,我得到 id 作为字符串。

$alphabets = new Alphabet();
return $alphabets->pluck('name', 'id');

输出

{
    "1": "Apple",
    "2": "Ball",
    "3": "Cat"
}

预计

{
    1: "Apple",
    2: "Ball",
    3: "Cat"
}

但是,当我反转 IDname 时,

return $alphabets->pluck('id', 'name');

我得到 id 作为整数。

{
    "Apple": 1,
    "Ball": 2,
    "Cat": 3
}

我不确定幕后发生了什么。但是我怎样才能得到整数 ID 呢?实际上,由于 Form Collective 中的 1 vs "1",旧的 Flash 会话没有设置值。

{!! Form::select('alphabet', $alphabets, null, ['class' => 'form-control', 'multiple' => true]) !!}

试试这个代码

$alphabets = new Alphabet();
return $alphabets->all()->pluck('name', 'id');

Alphabet.php

你应该像这样投你的专栏。

  protected $casts = [
    'id' => 'integer',
    'name' => 'string' 
  ];

通常,pluck() 方法为您提供值的关联数组 在字符串值中。

因此,请尝试使用 select 语句,如下所示:

$data = Alphabet::select('id','name')->get()->toArray();

这会给你以下结果:

array:3 [▼
  0 => array:2 [▼
    "id" => 1
    "name" => "Apple"
  ]
  1 => array:2 [▼
    "id" => 2
    "name" => "Ball"
  ]
  2 => array:2 [▼
    "id" => 3
    "name" => "Cat"
  ]
]

现在,使用简单的循环就可以获得预期的数组。

$expected = array();

foreach($data as $d){
    $expected[$d['name']] = $d['id'];
}

dd($expected);

你也将 key 转换成 int

 $alphabets = new Alphabet();
    $alphaArr =$alphabets->pluck('name', 'id');
    foreach($array as $key => $value) {
       $newArray[(int) $key] = $value;
    }

我想我在这里找到了答案。

https://laracasts.com/discuss/channels/laravel/pluck-id-integer-cast-to-string

这里我发现JSON只允许键名是字符串

Using number as "index" (JSON)

{
    "1": "Apple",
    "2": "Ball",
    "3": "Cat"
}

其实我是想Form Collective实现的。这是一个错误,现在它的 PR 已经合并了。

https://github.com/LaravelCollective/html/pull/368#pullrequestreview-46820423

添加此行修复了 LaravelCollective/Html.

的旧会话问题

|| in_array((string) $value, $selected, true)

/**
 * Determine if the value is selected.
 *
 * @param  string $value
 * @param  string $selected
 *
 * @return null|string
 */
protected function getSelectedValue($value, $selected)
{
    if (is_array($selected)) {
        return in_array($value, $selected, true) || in_array((string) $value, $selected, true) ? 'selected' : null;
    } elseif ($selected instanceof Collection) {
        return $selected->contains($value) ? 'selected' : null;
    }
    return ((string) $value == (string) $selected) ? 'selected' : null;
}