如果通过 laravel5 pluck(lists) 方法创建,如何将字符串添加到数组键?

How to add strings to array key if that made by laravel5 pluck(lists) method?

昨天解决了,谢谢大家

下一个问题。不是很重要,但我很担心,看这个代码。

控制器

$months = \App\Test::select(\DB::raw('DATE_PART(\'MONTH\', date) AS MONTH'))
                    ->where('date', '<=', 'now()')
                    ->orderBy('date', 'desc')
                    ->pluck('month', 'month');
                    // this code generate like this.
                    // Illuminate\Support\Collection Object ( [items:protected] => Array ( [8] => 8 [7] => 7 ) )

查看

{{ Form::select('month', $months, old('month'), ['id' => 'month']) }}

( now generate this. )

<select id="month" name="month">
    <option value="8">8</option>
    <option value="7">7</option>
</select>

我希望像这样给键添加字符串

<select id="month" name="month">
    <option value="8">8month</option>
    <option value="7">7month</option>
</select>

我认为可以像这样使用 foreach。

$array = ["8" => "8", "7" => "7"];

print_r($array); // Array ( [8] => 8 [7] => 7 )

foreach($array as $key => $value){
    $array[$key.'month'] = $value;
    unset($array[$key]);
}

print_r($array); // well done! Array ( [8month] => 8 [7month] => 7 )

所以测试一下但是...

print_r($months); // Illuminate\Support\Collection Object ( [items:protected] => Array ( [8] => 8 [7] => 7 ) )

foreach($months as $key => $value){
    $array[$key.'month'] = $value;
    unset($months[$array]);
}

print_r($months); // Not Working WTF!! Illuminate\Support\Collection Object ( [items:protected] => Array ( ) )

有解决办法吗?

您的 $months 变量是 Collection 实例。您可以使用 $months->put($key, $value)$months->push($value) 查看收集方法 here

编辑:

此外,我注意到您在第二个示例中使用了错误的变量。不应该是这样吗?

foreach($months as $key => $value){
    $months[$key.'month'] = $value;
    unset($months[$key]);
}

那个错误就是答案lmao XD 真的很努力,原谅我的愚蠢。

foreach($months as $key => $value){
    $months[$key.'month'] = $value;
    unset($months[$key]);
}

P.S.

以上代码是错误

此代码为真。

foreach($months as $key => $value){
    $months[$value] = $value.'month';
}