【问题标题】:Get specific value from array in laravel从 laravel 中的数组中获取特定值
【发布时间】:2018-10-07 14:04:10
【问题描述】:

我正在使用 Laravel。这是我的数组 -

[{"emp_id":1,"shift":"first","status":"Present","is_unpaid":0,"start":"2018-03-21 08:00:00","结束":"2018-03-21 12:00:00"},{"emp_id":2,"shift":"first","status":"Present","is_unpaid":0,"start":"2018-03-21 08:00:00","结束":"2018-03-21 12:00:00"},{"emp_id":3,"shift":"first","status":"Present","is_unpaid":0,"start":"2018-03-21 08:00:00","结束":"2018-03-21 12:00:00"},{"emp_id":4,"shift":"first","status":"Present","is_unpaid":0,"start":"2018-03-21 08:00:00","结束":"2018-03-21 12:00:00"},{"emp_id":6,"shift":"first","status":"Present","is_unpaid":0,"start":"2018-03-21 08:00:00","结束":"2018-03-21 12:00:00"},{"emp_id":7,"shift":"first","status":"Present","is_unpaid":0,"start":"2018-03-21 08:00:00","end":"2018-03-21 12:00:00"}]

这是我的数组输出代码 -

if(empty($employee->emp_record) ){
            $sheet  = array();
        }else{
            $sheet = unserialize($employee->emp_record);
        }

        return $sheet;

我想获取 emp_id 的值并在视图中显示。当我使用return $sheet->emp_id;

试图获取非对象的属性 发生了这个错误。

【问题讨论】:

  • 您有多条记录,每条记录都包含一个emp_id,因此您需要选择返回哪条记录或像这样访问return $sheet[0]->emp_id;
  • 什么是输出:- var_export($sheet);?

标签: php mysql arrays laravel


【解决方案1】:

要仅获取第一条记录,您需要使用:-

return $sheet[0]->emp_id;

但如果你想要全部,然后应用如下循环:-

foreach($sheet as $shet){
  echo $shet->emp_id;
}

输出:- https://eval.in/995586

【讨论】:

    【解决方案2】:

    你可以使用pluck()函数来获取数组的第一条记录

    【讨论】:

      【解决方案3】:

      如果你想要全部,然后应用如下循环:-

          $sheet = [];
          if(!empty($employee->emp_record) ){
              foreach($sheet as $shet){
                  $sheet[] = [
                     "emp_id" => $shet->emp_id
                     //.....rest data set
                  ];
              }
          }
          return $sheet;
      

      【讨论】:

      • 请不要在 Stack Overflow 上发布纯代码答案。 (即使你看到其他用户这样做)你的回答给这个页面带来了什么新价值?为什么研究人员应该阅读/使用您的建议?
      猜你喜欢
      • 2019-10-23
      • 2020-07-09
      • 2015-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多