duan5731 2017-11-08 08:29
浏览 72
已采纳

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

My problem was to get the array employeeIds in an array outside a foreach

$jobCard

$jobCard contains an associative in my instance I get the employee_id in the array

$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] . " 
" .$jobCard['description_notes'];
}

$detail['notes'] = implode("
", $notes);
Console::Log('display', $detail);
  • 写回答

1条回答 默认 最新

  • douxing6532 2017-11-08 09:05
    关注

    My understanding of your question is that you want employee names for ids combined with the description notes. If so, then your iteration logic is a bit mixed up.

    A simpler way is to:

    1. get all employees
    2. iterate $jobCards and compile the note while looking up the employee name in the employees array

    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
    %s",
            // access the employee name directly
            $employees[$jobCard['employee_id']]->getName(),
            $jobCard['description_notes']
        );
    }, $jobCards);
    
    $detail['notes'] = implode("
    ", $notes);
    

    function reference:

    array_column, array_map

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?