如何使用Php在foreach之外获取具有特定索引的数组

时间:2017-11-08 08:29:31

标签: php arrays foreach console display

我的问题是将数组employeeIds放在foreach之外的数组中

$jobCard

$ jobCard在我的实例中包含一个关联,我在数组中获得了employee_id

$employeeId = array();  

foreach ($jobCards as $jobCard) {
    $employeeId[] = $jobCard['employee_id'];
}

$employees = Employee::LoadArray($employeeId); 

foreach ($employees as $employeeID => $Employee) {
    $employeeName[$employeeID] = $Employee->getName();
    Console::Log('name', $employeeName);
}

foreach ($jobCards as $jobCard) {
    Console::Log('$employeeName', $employeeName);
    $notes[] = $employeeName[$employeeID] . " \n" .$jobCard['description_notes'];
}

$detail['notes'] = implode("\n", $notes);
Console::Log('display', $detail);

1 个答案:

答案 0 :(得分:1)

我对您的问题的理解是,您希望将ID的员工姓名与说明注释相结合。如果是这样,那么你的迭代逻辑有点混乱。

更简单的方法是:

  1. 让所有员工
  2. 迭代$jobCards并在查看employees数组中的员工姓名时编译注释
  3. E.g:

    <?php
    // get all employees for the collected ids
    $employees = Employee::LoadArray(array_column($jobCards, 'employee_id'));
    
    // map job cards to notes
    $notes = array_map(function ($jobCard) use($employees) {
        return sprintf(
            "%s\n%s",
            // access the employee name directly
            $employees[$jobCard['employee_id']]->getName(),
            $jobCard['description_notes']
        );
    }, $jobCards);
    
    $detail['notes'] = implode("\n", $notes);
    

    功能参考:

    array_columnarray_map