PHP 将字符串数组操作成关联数组

PHP manipulate array of string into an associative array

我有一个这样的数组:

array(4) {

  [0] => "1. \Device\NPF_{1AAAAA99-7933-4CBC-AF26-2A1C1394BD94} (VirtualBox Host-Only Network)"

  [1] => "2. \Device\NPF_{2BBBBB88-75BB-4CD0-970A-36430287C245} (Wireless Network Connection 6)"

  [2] => "3. \Device\NPF_{3CCCCC77-8469-4445-A2ED-9C0FDDBA1C3D} (Wireless Network Connection 7)"

  [3] => "4. \Device\NPF_{4EEEEE66-2C9D-4D47-B7EA-8A20A40A149B} (Local Area Connection)"

}

并想像这样操作成一个新的关联数组

array(4) {

  ["1"] => "VirtualBox Host-Only Network"

  ["2"] => "Wireless Network Connection 6"

  ["3"] => "Wireless Network Connection 7"

  ["4"] => "Local Area Connection"

}

我意识到我可以使用 foreach 循环遍历原始数组,然后在每次迭代中使用 substr 函数获取新数组键的第一个字符并查找 () 模式中的句子但失败了实现这一点。非常感谢任何建议!谢谢!

您的代码应如下所示,

<?php
$items_extended = array("1. \Device\NPF_{1AAAAA99-7933-4CBC-AF26-2A1C1394BD94} (VirtualBox Host-Only Network)", 
"2. \Device\NPF_{2BBBBB88-75BB-4CD0-970A-36430287C245} (Wireless Network Connection 6)", 
"3. \Device\NPF_{3CCCCC77-8469-4445-A2ED-9C0FDDBA1C3D} (Wireless Network Connection 7)", 
"4. \Device\NPF_{4EEEEE66-2C9D-4D47-B7EA-8A20A40A149B} (Local Area Connection)");
$items = array();
foreach($items_extended as $key => $value){
    preg_match('#\((.*?)\)#', $value, $match);
    $items[($key + 1)] = $match[0];
}
?>

尝试使用该代码:通过使用 foreach,它应该可以工作。测试正则表达式:http://www.phpliveregex.com/

<? 
var $arrInputs = array (......); // you put your array with data

var $arrest = [];
foreach ($arrInputs as $key => $input_line ){

preg_match("(^.).*[(](.*)[)]$", $input_line, $output_array);

$arrest[$output_array[1]] = $output_array[2];

}

print_r($arrest);


%>

在 php 中,您可以不使用循环来做到这一点:

$data = [
    "1. \Device\NPF_{1AAAAA99-7933-4CBC-AF26-2A1C1394BD94} (VirtualBox Host-Only Network)",
    "2. \Device\NPF_{2BBBBB88-75BB-4CD0-970A-36430287C245} (Wireless Network Connection 6)",
    "3. \Device\NPF_{3CCCCC77-8469-4445-A2ED-9C0FDDBA1C3D} (Wireless Network Connection 7)",
    "4. \Device\NPF_{4EEEEE66-2C9D-4D47-B7EA-8A20A40A149B} (Local Area Connection)",
    ];

$names = array_combine(
    preg_replace('~\D.*~', '', $data),
    preg_replace('~.*\((.+?)\)$~', '', $data));

print_r($names);

结果:

Array
(
    [1] => VirtualBox Host-Only Network
    [2] => Wireless Network Connection 6
    [3] => Wireless Network Connection 7
    [4] => Local Area Connection
)