从数组渲染数据以选择选项laravel

时间:2019-02-08 14:54:06

标签: laravel

function getAllYears()
{ 
    $year_array = array();
    $posts_dates = Entries::orderBy( 'created_at', 'ASC' )->pluck( 'created_at' );
    $posts_dates = json_decode( $posts_dates );

    if ( ! empty( $posts_dates ) ) 
    {
        foreach ( $posts_dates as $unformatted_date )
         {
            $date = new \DateTime( $unformatted_date->date );
            $year_value = $date->format( 'Y' );
            $year_val = $date->format( 'y' );

            //$year_array[$year_val ] = $year_value;
            $year_array[] = $year_value;
         }
    } //return $year_array;
    $array = $year_array;

//删除重复项 $ unique_years = array_unique($ array);

返回视图('welcome',compact($ unique_years));

<select name="YearFrom" id="YearFrom_input"">
    <option selected="selected">Choose Year</option>
    @foreach($unique_years as $years)
        <option value='{{$years}}'> {{$years['years']}} </option>
    @endforeach
</select>

!!出错!

  

compact():未定义的变量:2009

2 个答案:

答案 0 :(得分:0)

compact认为数组的值是变量名,因为您已经将其传递给了实际的数组,而不是变量名。有关compact()的工作方式的详细信息,请参见http://php.net/compact。相反,您需要:

return view('welcome',compact('unique_years'));

也就是说,出于这个原因,我讨厌compact方法。这更具可读性:

return view('welcome')->with('unique_years', $unique_years);

答案 1 :(得分:0)

您的variabel名称在compact()中不正确-应该是类似于'variable_name'的字符串,而不是$ variable_name

function getAllYears()
{
    $year_array = array();
    $posts_dates = Entries::orderBy( 'created_at', 'ASC' )->pluck( 'created_at' );
    $posts_dates = json_decode( $posts_dates );

    if ( ! empty( $posts_dates ) )  {
        foreach ( $posts_dates as $unformatted_date ) {
            $date = new \DateTime( $unformatted_date->date );
            $year_value = $date->format( 'Y' );
            $year_val = $date->format( 'y' );

            //$year_array[$year_val ] = $year_value;
            $year_array[] = $year_value;
        }
    } //return $year_array;

    $array = $year_array;

    // Deleting the duplicate items
    $unique_years = array_unique($array);

    return view('welcome',compact('unique_years'));
}