PHP关联数组变量赋值

时间:2016-07-18 23:18:42

标签: php arrays laravel

我将这段代码放在一个更大的函数中,该函数从HTTP Post(使用Laravel)中提取数据并将其放入数组中进行进一步处理。我觉得必须有一个更好的方法来完成将这些字段放入数组中,但我不确定如何。建议?

    $fields = array(
        'env' => $request->get('env'),
        'subtype' => $request->get('subtype'),
        'submitter' => $request->get('submitter'),
        'problemSummary' => $request->get('problemSummary'),
        'problemDescription' => $request->get('problemDescription'),
        'resolutionCode' => $request->get('resolutionCode'),
        'resolutionDetails' => $request->get('resolutionDetails'),
        'status' => $request->get('status'),
        'account' => $request->get('account'),
        'phone' => $request->get('phone'),
        'residenceHall' => $request->get('residenceHall'),
        'roomNumber' => $request->get('roomNumber'),
        'buildingName' => $request->get('buildingName'),
        'buildingNumber' => $request->get('buildingNumber'),
        'source' => $request->get('source'),
        'submittedVia' => $request->get('submittedVia'),
        'internalNotes' => $request->get('internalNotes'),
        'computerType' => $request->get('computerType'),
        'computerVendor' => $request->get('computerVendor'),
        'operatingSystem' => $request->get('operatingSystem'),
        'recentBackup' => $request->get('recentBackup'),
        'antiVirus' => $request->get('antiVirus'),
        'acceptAgreement' => $request->get('acceptAgreement'),
    );

2 个答案:

答案 0 :(得分:4)

出了什么问题:

$fields = $request->only('env', 'subtype', 'submitter', ... );

或:

$fieldNames = ['env', 'subtype', 'submitter', ...];
$fields = $request->only($fieldNames);

答案 1 :(得分:2)

你可以这样做:

// Define the field names you want to get from the request
/*
$fields = array(
    'env',
    'subtype',
    'submitter',
    ...
);
*/

$data = array();
foreach($fields as $v){
    $data[$v] = $request->get($v);
}

它只会从$fields中定义的请求的键中获取值,并且它将放在$data数组中的相同键中。