我需要php幫助/專業知識來調整/更改此preg_match_all函數。我想要做的是爲缺失的有序對創建默認值。它正確匹配數據,但我需要一些邏輯來添加一些默認值。 (請參閱下面的EXPECTING數據輸出)。這可以在這個相同的功能內處理嗎?謝謝!有關preg_match_all的幫助和創建默認值
preg_match_all片段:
foreach ($InputFile as $line){
preg_match_all("/([0-9])-([^=]+)=([^;]+);/", $line, $matches, PREG_SET_ORDER);
$LineData = array();
foreach ($matches as $information)
$LineData[$information[2]] = $information[3];
$data[] = $LineData;
print_r($LineData);
}
數據文件具有的(8)依次屬性一個最大:
1-Server
2-Logdate
3-BackupSet
4-StartTime
5-Duration
6-DBServer
7-Size
8-Status
但也有實例文件,那裏是做線不具有所有屬性,例如5-Duration,7-Size,8-Status。我想將默認值這些屬性是這樣的:
5-Duration => 0
7-Size => 0
8-Status => incomplete
陣列輸出:(當前)
Array ([Server] => hostname3.prop.abc
[Logdate] => Wed Jan 05 2011
[BackupSet] => rfoo101.az1
[StartTime] => 20110105000004
[Duration] => 00:56:47
[DBServer] => rfoo101.prop.az1.kaz.com
[Size] => 56.51
[Status] => Backup succeeded)
Array ([Server] => hostname3.prop.abc
[Logdate] => Wed Jan 05 2011
[BackupSet] => bar202.az4_lvm
[StartTime] => 20110105040003
[DBServer] => bar202.prop.az4.kaz.com)
Array ([Server] => hostname10.prop.az2
[Logdate] => Thu Jan 06 2011
[BackupSet] => bar201_az2_lvm
[StartTime] => 20110106151622
[DBServer] => bar201.prop.az2.kaz.com
[Status] => Backup failed)
期待數據輸出:(使用默認值)
Array ([Server] => hostname3.prop.abc
[Logdate] => Wed Jan 05 2011
[BackupSet] => rfoo101.az1
[StartTime] => 20110105000004
[Duration] => 00:56:47
[DBServer] => rfoo101.prop.az1.kaz.com
[Size] => 56.51
[Status] => Backup succeeded)
Array ([Server] => hostname3.prop.abc
[Logdate] => Wed Jan 05 2011
[BackupSet] => bar202.az4_lvm
[StartTime] => 20110105040003
[Duration] => 0
[DBServer] => bar202.prop.az4.kaz.com
[Size] => 0
[Status] => incomplete)
Array ([Server] => hostname10.prop.az2
[Logdate] => Thu Jan 06 2011
[BackupSet] => bar201_az2_lvm
[StartTime] => 20110106151622
[Duration] => 0
[DBServer] => bar201.prop.az2.kaz.com
[Size] => 0
[Status] => Backup failed)
代碼幫助更改:
<?php
$defaults = array(
'Duration' => 0,
'Size' => 0,
'Status' => 'incomplete');
$data = array();
$InputFile = file("test.txt");
foreach ($InputFile as $line){
preg_match_all("/([0-9])-([^=]+)=([^;]+);/", $line, $matches, PREG_SET_ORDER);
$LineData = array();
foreach ($matches as $information)
$LineData[$information[2]] = $information[3];
$data[] = array_merge($defaults, $LineData);
}
print_r($data);
?>
很有意思。我會在foreach中的preg_match_all函數之後插入這個函數嗎?謝謝。 – cjd143SD 2011-01-11 06:39:24
我編輯了一個更詳細的解釋你的特殊情況。 – Amber 2011-01-11 06:43:22