用于创建具有有意义键名的动态数组的快捷方式


shortcut for creating dynamic array with meaningful key names

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

 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));
   }
}

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

要回答您最初的问题,您可以使用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]));
}