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

时间:2015-01-23 15:43:16

标签: php arrays string 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函数来获取新数组键的第一个char并查找()模式中的句子但是未能实现这个。任何建议都非常感谢!谢谢!

3 个答案:

答案 0 :(得分:3)

在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('~.*\((.+?)\)$~', '$1', $data));

print_r($names);

结果:

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

答案 1 :(得分:0)

您的代码看起来应该是这样的,

<?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];
}
?>

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


%>