0

菜鸟问题。我有这个:

Array
(
    [0] => address = 123 Something Street
    [1] => address2 = Something else
    [2] => city = Kalamazoo
    [3] => state = MI
    [4] => zip = 49097
    [5] => country = United States
)

但我想要这个:

Array
(
    [address] => 123 Something Street
    [address2] => Something else
    [city] => Kalamazoo
    [state] => MI
    [zip] => 49097
    [country] => United States
)

我该怎么做呢?谢谢!

4

4 回答 4

9

试试这个:

$new_array = array();
foreach($your_array as $line) {
 list($key, $value) = explode('=', $line, 2);
 $new_array[$key] = $value;
}

访问$new_array

于 2012-05-11T15:40:11.060 回答
3

您需要遍历数组并将值分解为“=”之前的位和之后的位。使用这两条数据,您可以创建一个新数组,该数组由第一位索引,并将值作为第二位。

$new_array = array();
foreach($your_array as $value)
{
    $chunks = explode(' = ', $value);
    $key = $chunks[0];
    $new_array[$key] = $chunks[1];
}
于 2012-05-11T15:42:27.720 回答
1
$arrayOriginal = Array
(
    [0] => address = 123 Something Street
    [1] => address2 = Something else
    [2] => city = Kalamazoo
    [3] => state = MI
    [4] => zip = 49097
    [5] => country = United States
);
$arrayNew = Array();
for($arrayOriginal as $value)
{
    $strArray = explode(" = ", $value, 2);
    $arrayNew[$strArray[0]] = $stArray[1];
}

需要注意的一点是,如果您的数组不太可能完全格式化,请执行以下操作:

for($arrayOriginal as $value)
{
    $strArray = explode("=", $value, 2);
    $arrayNew[trim($strArray[0])] = trim($strArray[1]);
}

这确保了即使像“something = something”这样的值也会被正确解析。

于 2012-05-11T15:42:04.820 回答
0

我不相信有任何功能可以自动为您执行此操作,但我只是写了以下内容。

$newArr = array();
foreach ($oldArr as $value) {
    $split = explode(" = ", $value, 2);
    $newArr[$split[0]] = $split[1];
}
于 2012-05-11T15:43:42.470 回答