qwe001 qwe001 - 3 months ago 13
PHP Question

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

Yesterday I solved this issue, Thanks Everyone.

Next problem. Not so important but I feel concern, Look this code.

Controller

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


View

{{ 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>


I hope to add string to key like this

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


I think that can do with foreach like this.

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


So test it but...

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


Any Solves?

Answer

that mistake is the answer lmao XD truly work this, forgive my stupid.

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

P.S.

Above Code is MISTAKE

This Code is true.

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