我正在尝试创建一个多维数组,但是内部一直使用foreach中数组的最后一个值。
我正在使用PHP 7.3和Laravel 5.8。我试过对该区域进行一次foreach,然后对位置进行一次foreach,在内部对信息进行一次foreach。 我正在使用的正则表达式是:
// Define regex for each of the required fields
$location_regex = '/----(.*)-----/m';
$total_regex = '/^.*\bTotal\b.*/m';
$age_regex = '/Age (?:DAYS (\d+))/m';
// Perform the regex
preg_match_all($location_regex, $message, $locations, PREG_SET_ORDER, 0);
preg_match_all($age_regex, $message, $ageMatches, PREG_SET_ORDER, 0);
preg_match_all($total_regex, $message, $totalMatches, PREG_SET_ORDER, 0);
然后,当然$ ageMatches和$ totalMatches将作为数组返回。
我正在使用正则表达式从以下纯文本电子邮件中获取值:
"""
ELY FARM
THE ADDRESS
BW8010 2.55 UNIT 1
Logged 03 JUN 19 23:59
SUMMARY REPORT
----UNIT 1 PERCH 1-----
House 1, Pen 1
Age DAYS 7
Total 3997
Average GMS 64
Deviation GMS 14
Evenness % 29
C.V. % 21.9
Daily gain GMS 9
----UNIT 1 PERCH 2-----
House 1, Pen 2
Age DAYS 7
Total 3849
Average GMS 73
Deviation GMS 17
Evenness % 29
C.V. % 23.3
Daily gain GMS 9
----UNIT 1 PERCH 9-----
House 3, Pen 3
Age DAYS 7
Total 3614
Average GMS 67
Deviation GMS 16
Evenness % 23
C.V. % 23.9
Daily gain GMS 8
我的数据是
// Go through each message
foreach ($aMessage as $oMessage) {
// Get address from email subject
$address = $oMessage->getSubject(true);
// Add the address to an array
$email_data = array($address);
// Add the sub location to each address in the array
foreach ($locations as $location) {
$email_data[$address][$location[1]] = array();
// Add the data to the sub location in the array
foreach ($ageMatches as $ageIndex => $age) {
$email_data[$address][$location[1]]['Age'] = $age[1];
}
foreach ($totalMatches as $totalIndex => $total) {
$total['Total'] = preg_replace('/[^0-9]/', '', $total);
$email_data[$address][$location[1]]['Total'] = $total['Total'][0];
}
}
dd($email_data);
}
当前输出为:
array:2 [▼
0 => "Ely Farm"
"Ely Farm" => array:10 [▼
"UNIT 1 PERCH 1" => array:7 [▼
"Age" => "7"
"Total" => "3614"
"Average" => "67"
"Deviation" => "16"
"Evenness" => "23"
"C.V." => "..23.9"
"Daily Gain" => "8"
]
"UNIT 1 PERCH 2" => array:7 [▼
"Age" => "7"
"Total" => "3614"
"Average" => "67"
"Deviation" => "16"
"Evenness" => "23"
"C.V." => "..23.9"
"Daily Gain" => "8"
]
我希望得到:
array:2 [▼
0 => "Ely Farm"
"Ely Farm" => array:10 [▼
"UNIT 1 PERCH 1" => array:7 [▼
"Age" => "7"
"Total" => "3997"
"Average" => "64"
"Deviation" => "14"
"Evenness" => "29"
"C.V." => "..21.9"
"Daily Gain" => "9"
]
"UNIT 1 PERCH 2" => array:7 [▼
"Age" => "7"
"Total" => "3849"
"Average" => "73"
"Deviation" => "17"
"Evenness" => "29"
"C.V." => "..23.9"
"Daily Gain" => "9"
]
答案 0 :(得分:0)
据我了解,您的正则表达式并未提取所有数据。仅返回最后一次出现的匹配数据。
您的正则表达式使用'm'修饰符。该修饰符表示多行输入。但是正则表达式需要使用'^'和'$'字符指示输入的开始和结束。请参阅Regular Expression Pattern modifiers的文档。