如何添加字符串数组键,如果是由laravel5拔(列表)方法


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>

我想这对每个人都可以。

$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 ( ) )

解决吗?

这个错误就是答案lmao XD真心实意的工作这个,原谅我的愚蠢。

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

公立小学

以上代码为错误

This Code is true.

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

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

编辑:

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

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