php - 使用有意义的键名创建动态数组的快捷方式

时间:2012-08-17 23:08:44

标签: php regex

我有一些逻辑可以根据正则表达式中的匹配构建多维数组。我使用分隔符调用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函数。每次我找到一个“〜”,我知道它是一个新字段的开始,所以我可以手动添加它们的键/值对。 但我只是想知道是否有人有其他方法来做这个想法。 谢谢。

1 个答案:

答案 0 :(得分: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]));
}