Reputation: 1338
Noob question. I have this:
Array
(
[0] => address = 123 Something Street
[1] => address2 = Something else
[2] => city = Kalamazoo
[3] => state = MI
[4] => zip = 49097
[5] => country = United States
)
but I want this:
Array
(
[address] => 123 Something Street
[address2] => Something else
[city] => Kalamazoo
[state] => MI
[zip] => 49097
[country] => United States
)
How do I do this? Thanks!
Upvotes: 0
Views: 158
Reputation: 28687
I don't believe there is any function to do this automatically for you, but I just wrote up the following.
$newArr = array();
foreach ($oldArr as $value) {
$split = explode(" = ", $value, 2);
$newArr[$split[0]] = $split[1];
}
Upvotes: 0
Reputation: 172
You need to loop through the array and break up the value into the bit before the ' = ' and the bit after. using these two pieces of data you can create a new array which is indexed by the first bit and has the value as the second bit.
$new_array = array();
foreach($your_array as $value)
{
$chunks = explode(' = ', $value);
$key = $chunks[0];
$new_array[$key] = $chunks[1];
}
Upvotes: 3
Reputation: 3616
$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];
}
A small thing to note, if your array is not likely to be exactly formatted, instead do:
for($arrayOriginal as $value)
{
$strArray = explode("=", $value, 2);
$arrayNew[trim($strArray[0])] = trim($strArray[1]);
}
This ensures that even values like "something = something" will be parsed correctly.
Upvotes: 1
Reputation: 1950
Try this:
$new_array = array();
foreach($your_array as $line) {
list($key, $value) = explode('=', $line, 2);
$new_array[$key] = $value;
}
Access $new_array
.
Upvotes: 9