从嵌套数组中获取SQL列值

时间:2014-11-27 08:25:28

标签: php sql database laravel eloquent

这里更好地解释这是我的代码:

        $mydate=Carbon::now()->addHours(8);
        $newdate=$mydate->toDateString();

        $myquery = DB::table('attendances')->where('date_only', '=', $newdate)->orderBy('logon','asc')->get();

        $counter=0;
        foreach ($myquery as $newquery) 
        {
        $query1[$counter]=$newquery->user_id;

        $finalquery[$counter]= DB::table('employees')->where('id', '=', $query1[$counter])->get();
        $counter++;

        }

        var_dump($finalquery[2]);

此代码的输出将为:

      array(1) { [0]=> object(stdClass)#160 (6) { ["id"]=> int(23) ["firstname"]=> string(3) "Kim" ["lastname"]=> string(7) "Samsung" ["position"]=> string(10) "Programmer" ["created_at"]=> string(19) "2014-11-25 07:21:31" ["updated_at"]=> string(19) "2014-11-25 07:21:31" } } 

我想要做的是访问其中一个值,所以我尝试了这个

         //I change
         var_dump($finalquery[2]);
         //to this
         var_dump($finalquery[2]->firstname);

但我得到的只是错误。错误代码500

2 个答案:

答案 0 :(得分:1)

试试这个

   // not necessary
  foreach ($myquery as $key => $newquery) 
    {
        $query1[$key]=$newquery->user_id;
        $finalquery[$key]= DB::table('employees')->where('id', '=', $query1[$key])->get();
    }

    // necessary

    print_r($finalquery->toArray());  // if its array of objects I'm converting it into an array
        // or
    print_r($finalquery);

修改好友我的建议是使用joins此单个查询可以让您获得所有数据,无需使用带有多个查询的foreach Reference < / p>

$myquery = DB::table('attendances')->select('employees.id as emp_id','attendances.id as att_id',/*your fields*/)
        ->leftJoin('employees', 'employees.id','=','attendances.id')
        ->where('date_only', '=', $newdate)
        ->orderBy('attendances.logon','asc')->get();


    print_r($myquery->toArray());
控制器中的

 return View::make('home', array('mydata' => $finalquery)); 

在视图中:(对于刀片)

@if($mydata && count($mydata) > 0)
    @foreach($mydata as $data)

        {{ $data->id }}<br>
        {{ $data->name }}<br>
        {{ $data->etc }}<br>

    @endforeach
@else
    <p>sorry no data to display</p>
@endif

答案 1 :(得分:0)

您的var_dump建议finalquery[2]是一个对象数组,而不是对象本身。所以这不会起作用

var_dump($finalquery[2]->firstname);

这将

var_dump($finalquery[2][0]->firstname);

foreach($finalquery[2] as $obj)
{
      echo $obj->firstname;
}