开发者

array to assoc

开发者 https://www.devze.com 2023-02-21 20:22 出处:网络
I have an array Array ( [0] => [RESPONSE] [1] => DESCRIPTION=Attribute value is not unique [2] => CODE=540

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);
?>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号