【问题标题】:PHP: Separate values in foreach according to keyPHP:根据键在foreach中分隔值
【发布时间】:2016-10-14 06:53:45
【问题描述】:

我正在使用 PHP Laravel。

我需要获取每位员工的总时间/小时数。每个员工都有一个分配的 timeKeeping_empID。 Time_Logs 表有以timeKeeping_empID为外键的Employees的时间日志。

我尝试运行我的代码: 控制器:

function getTotalHours(Request $request)
        {

            $team = Employees::where('managerID', $request->session()->get('employeeID'))->get();
                //I am assigning an array to be grouped according to my employeeID session.
                $teamIDs = array();
                //I am getting my own session so I can see my data as well together with my team
                array_push($teamIDs, $request->session()->get('employeeID'));
                foreach($team as $member) {
                    array_push($teamIDs, $member->employeeID);
                }
                //I am getting the column employeeID which is the same with the teamID
                $empData = Employees::whereIn('employeeID', $teamIDs)->get();
                $timeKeepingIDs = array();
                foreach($empData as $anEmpData) {
                    array_push($timeKeepingIDs, $anEmpData->timeKeeping_empID);
                }
                $timeLogData = Time_Logs::whereIn('timeKeeping_empID', $timeKeepingIDs)->get();

            return view('welcome', compact('timeLogData','request'));
        }

在我看来: $totalHours=0;

        foreach ($timeLogData as $timeLogDatas) {

        $dateToday = new DateTime($timeLogDatas->date);
        $timeFrom = date_create($timeLogDatas->time_in);
        $timeTo = date_create($timeLogDatas->time_out);
        $hoursRendered = date_diff($timeFrom, $timeTo);

        $totalHours=$totalHours += (int) $hoursRendered->format('%h');
        }
        echo "$totalHours";

但结果是所有员工的总小时数。 我需要的是每个员工的总小时数。

这是我的数据库表:

(Employee) 
EmployeeID (primaryKey) 
timeKeeping_empID 
name


(Time_Logs)
id(primaryKey)
timeKeeping_empID
date
time-in
time-out

对不起,我是 PHP 新手。

【问题讨论】:

  • 如果您包含对数据库表的描述会有所帮助
  • 另外,当你与每个员工循环时,你应该将总小时数归零。
  • 已更新。与数据库表。
  • 您可以在查询中使用聚合函数 SUM('YOUR-TIME-COL') 和 GROUP BY timeKeeping_empID

标签: php laravel sorting foreach


【解决方案1】:

作为 MVC 模式的原则,您永远不应该将应用程序逻辑放在视图中;将你所有的计算逻辑放在Controller中,然后在你的视图中输出计算值。

话虽如此,您之所以要获取所有员工的时间数据,是因为您将整个员工 ID 号数组传递给了 Timelogdata 的 Where 子句:

$timeLogData = Time_Logs::whereIn('timeKeeping_empID',$timeKeepingIDs)->get();

通过传递员工编号数组,您实际上是在 $timeKeepingIDs 数组中获取所有员工的综合时间日志。

有很多方法可以解决这个问题,但最简单的可能是为每个员工的所有总小时数创建一个关联数组。您必须遍历 $empData 数组中的每个员工,执行计算,并保存一个单独的 $timesheets 数组,如:

//I am getting the column employeeID which is the same with the teamID
$empData = Employees::whereIn('employeeID', $teamIDs)->get();

$timesheets = array();
foreach($empData as $anEmpData) {
    $timeLogData = Time_Logs::whereIn('timeKeeping_empID', $anEmpData->timeKeeping_empID)->get();

    $totalHours = 0;

    $timeLogs = array();
    foreach($timeLogData as &$t) {
        $timeData['dateToday'] = new DateTime($t->date);
        $timeData['timeFrom'] = date_create($t->time_in);
        $timeData['timeTo'] = date_create($t->time_out);
        $timeData['hoursRendered'] = date_diff($timeFrom, $timeTo);
        array_push($timeLogs, $timeData);

        $totalHours=$totalHours += (int) $hoursRendered->format('%h');
    }

    $timesheets[$anEmpData->timeKeeping_empID] = [ 'timeLogs' => $timeLogs, 'totalHours' => $totalHours ];
}

return view('welcome', compact('timesheets','request'));

现在,在您看来,您可以使用@foreach Blade 指令:

<?php
@foreach ($timesheets as $empid => $timesheet)
<p>Timesheet for employee id $empid</p>

    @foreach ($timesheet['timeLogs'] as $timeLog)
        <ul>
        @foreach ($timeLog as $logEntry)

            <li>Date: $logEntry['dateToday']</li>
            <li>Time In: $logEntry['timeFrom']</li>
            <li>Time Out: $logEntry['timeTo']</li>
            <li>Hours rendered: $logEntry['hoursRendered']</li>

        @endforeach
        </ul>
    @endforeach

    Total hours rendered is: $timesheet['totalHours']
@endforeach
?>

我还没有在我的电脑上测试过这个,但我希望你能明白。

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    我认为你应该做的是一个小时数组,而不是把它们加在一起:

        foreach ($timeLogData as $timeLogDatas) {
    
        $dateToday = new DateTime($timeLogDatas->date);
        $timeFrom = date_create($timeLogDatas->time_in);
        $timeTo = date_create($timeLogDatas->time_out);
        $hoursRendered = date_diff($timeFrom, $timeTo);
    
        $totalHours[$timeLogDatas->timeKeeping_empID] = $totalHours[$timeLogDatas->timeKeeping_empID] + (int) $hoursRendered->format('%h');
        }
        print_r("$totalHours");
    

    然后您将获得一个包含员工总小时数的数组。 然后你会得到一个像这样的输出:

    Array
    (
        [123] => 120
        [124] => 95
        [129] => 195
    )
    

    其中键是员工 ID,值是他的总小时数。

    【讨论】:

    • 它说“不能将标量值用作数组”
    • 您是否尝试将变量声明为数组,例如$totalHours=array();
    • 是的。我尝试更改 $totalHours=0;到 $totalHours=array();但出现另一个错误并显示 "Undefine Offset: 5" 。而且我认为这与数组有关。
    • 你在哪一行得到了错误?在我们看到的代码之后,您是否对这个数组进行了额外的处理?
    • 也许您正在对员工使用 foreach,当您对第五名员工(id = 5 的员工)执行 $totalHours[$anEmpData-&gt;EmployeeID] 时,time_logs 表中没有匹配项。如果您正在做类似的事情,请在之前添加 if (!empty($totalHours[$anEmpData-&gt;EmployeeID])) 以确保他已设置在数组中
    【解决方案3】:

    嘿,我会向你展示 Laravel 魔法:P

    function getTotalHours(Request $request)
    {
    $timeLogData = Time_Logs::groupBy('timeKeeping_empID')->selectRaw('sum(time_out-time_in) as workingHours, timeKeeping_empID')->lists('workingHours','timeKeeping_empID');
    }
    

    在你看来

    foreach ($timeLogData as $timeLogDatas) {
    {{$timeLogDatas->user->name}} - {{$timeLogDatas->workingHours}}
    } 
    

    在您的 Time_Logs 模型中,您必须使用此功能

    public function user()
        {
            return $this->belongsTo('App\Employee','EmployeeID');
        }
    

    额外:我想你必须在你的 Time_Logs

    中使用它
    protected $dates = [
            'log_in',
            'log_out',
    
        ];
    

    【讨论】:

    • 我尝试使用您的代码,但出现错误,它显示“尝试获取非对象的属性”。 :(
    • @PatriciaArante 首先检查你的控制器函数 dd($timeLogData) 你会得到输出吗?让我知道
    • @PatriciaArante 嘿,我以为你从用户表中获取员工姓名现在检查我的答案...检查 Time_Logs 模型中的 user() 函数
    • @PatriciaArante 尝试获取属性 :)
    猜你喜欢
    • 2016-05-19
    • 2017-02-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-22
    • 1970-01-01
    • 2011-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多