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 に答える