0

我有一些逻辑可以根据正则表达式中的匹配项构建多维数组。我使用分隔符调用explode函数。一切正常,我的数组如下所示:

 Array ( 
  [0] => 
    Array ( 
        [0] => A1 
        [1] => 100/1000T 
        [2] => No 
        [3] => Yes 
        [4] => Down 
        [5] => 1000FDx 
        [6] => Auto 
        [7] => off 
        [8] => 0 
    ) 
[1] => Array ( 
        [0] => A2 
        [1] => 100/1000T 
        [2] => No 
        [3] => Yes 
        [4] => Down 
        [5] => 1000FDx 
        [6] => Auto 
        [7] => off 
        [8] => 0 
      ) etc.etc...

为了使前端的代码保持“哑”,我想将键从数字更改为代表值的字符串。这些字符串将用作表格中的列标题。例如:

 Array ( 
  [0] => 
    Array ( 
        [port] => A1 
        [Type] => 100/1000T 
        [Alert] => No 
        [Enabled] => Yes 
        [Status] => Down 
        [Mode] => 1000FDx 
        [MDIMode] => Auto 
        [FlowCtrl] => off 
        [BcastLimit] => 0 
    ) 
[1] => Array ( 
        [port] => A2 
        [Type] => 100/1000T 
        [Alert] => No 
        [Enabled] => Yes 
        [Status] => Down 
        [Mode] => 1000FDx 
        [MDIMode] => Auto 
        [FlowCtrl] => off 
        [BcastLimit] => 0         
               ) etc.etc...

下面是生成这个数组的代码:

  $portdetailsArray = array();
  foreach ($data as $portdetails) {
    $pattern = '/(\s+)([0-9a-z]*)(\s+)(100\/1000T|10|\s+)(\s*)(\|)(\s+)(\w+)(\s+)(\w+)(\s+)(\w+)(\s+)(1000FDx|\s+)(\s*)(\w+)(\s*)(\w+|\s+)(\s*)(0)/i';

   if (preg_match($pattern, $portdetails, $matches)) {

        $replacement = '$2~$4~$8~$10~$12~$14~$16~$18~$20';
        $portdetails= preg_replace($pattern, $replacement, $portdetails);
        array_push($portdetailsArray, explode('~',$portdetails));
   }

}

我想我可以手动循环遍历我的字符串,而不是使用explode函数。每次我找到一个“~”时,我都知道这是一个新字段的开始,所以我可以手动添加它们的键/值对。但我只是想知道是否有人对其他方法有想法。谢谢。

4

1 回答 1

2

要回答您的原始问题,您可以使用该array_combine功能来更换密钥。

$row = explode('~',$portdetails);
$row = array_combine(array(
       'port',
       'Type',
       'Alert',
       'Enabled',
       'Status',
       'Mode',
       'MDIMode',
       'FlowCtrl',
       'BcastLimit'), $row);

但更好的是,您应该使用更清晰的(在这种情况下,冗长更清晰)

if (preg_match($pattern, $portdetails, $matches)) {
    array_push($portdetailsArray, array(
       'port' => $matches[2],
       'Type' => $matches[4],
       'Alert' => $matches[8],
       'Enabled' => $matches[10],
       'Status' => $matches[12],
       'Mode' => $matches[14],
       'MDIMode' => $matches[16],
       'FlowCtrl' => $matches[18],
       'BcastLimit' => $matches[20]));
}
于 2012-08-17T23:19:40.733 回答