array to assoc
I have an array
Array
(
[0] => [RESPONSE]
[1] => DESCRIPTION=Attribute value is not unique
[2] => CODE=540
[3] =>
[4] => QUEUETIME=0.003
[5] => RUNTIME=0.003
[6] =>
[7] => EOF
)
Array
And I want to make it into
array( [DESCRIPTION] => Attribute value is not unique, [CODE] => 540 ...);
How 开发者_如何学编程can I do this? I can't use the explode because it is an array?
If this is what I think it is, why not use PHP's built-in parse_ini_file() function to read the file into an associative array automatically? or parse_ini_string() if it's not coming from a file source?
I do not believe that PHP has one, but heres a simple function to do it (tested):
$array2 = array();
foreach($array1 as $value)
{
$values = explode("=", $value);
if(count($values) > 1)
{
$newValue = "";
for($i = 1; $i < count($values); $i++)
{
$newValue .= $values[$i];
}
$array2[$values[0]] = $newValue;
}
else
{
$array2[] = $value;
}
}
Whilst a bit of a brute force approach, the following should work:
<?php
$testArray = array('[RESPONSE]', 'DESCRIPTION=Attribute value is not unique', 'CODE=540', 'QUEUETIME=0.003', 'RUNTIME=0.003');
$newArray = array();
foreach($testArray as $element) {
if(strpos($element, '=') !== false) {
list($key, $value) = explode('=', $element, 2);
$newArray[$key] = $value;
}
}
print_r($newArray);
?>
精彩评论