Noob问题。我有这个:
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
)
我该怎么做?谢谢!
答案 0 :(得分:9)
试试这个:
$new_array = array();
foreach($your_array as $line) {
list($key, $value) = explode('=', $line, 2);
$new_array[$key] = $value;
}
访问$new_array
。
答案 1 :(得分:3)
您需要遍历数组并将值分解为'='之前的位和之后的位。使用这两个数据,您可以创建一个新数组,该数组由第一位索引,并将值作为第二位。
$new_array = array();
foreach($your_array as $value)
{
$chunks = explode(' = ', $value);
$key = $chunks[0];
$new_array[$key] = $chunks[1];
}
答案 2 :(得分: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”这样的值。
答案 3 :(得分:0)
我不相信有任何功能可以自动为您执行此操作,但我刚刚写了以下内容。
$newArr = array();
foreach ($oldArr as $value) {
$split = explode(" = ", $value, 2);
$newArr[$split[0]] = $split[1];
}