explode() into $key=>$value pair

后端 未结 15 620
广开言路
广开言路 2020-12-01 09:24

I have this:

$strVar = \"key value\";

And I want to get it in this:

array(\'key\'=>\'value\')

I tried

相关标签:
15条回答
  • If you have long list of key-value pairs delimited by the same character that also delimits the key and value, this function does the trick.

    function extractKeyValuePairs(string $string, string $delimiter = ' ') : array
    {
        $params = explode($delimiter, $string);
    
        $pairs = [];
        for ($i = 0; $i < count($params); $i++) {
            $pairs[$params[$i]] = $params[++$i];
        }
    
        return $pairs;
    }
    

    Example:

    $pairs = extractKeyValuePairs('one foo two bar three baz');
    
    [
        'one'   => 'foo',
        'two'   => 'bar',
        'three' => 'baz',
    ]
    
    0 讨论(0)
  • 2020-12-01 09:55

    Don't believe this is possible in a single operation, but this should do the trick:

    list($k, $v) = explode(' ', $strVal);
    $result[ $k ] = $v;
    
    0 讨论(0)
  • 2020-12-01 09:55

    I found another easy way to do that:

    $a = array_flip(explode(' ', $strVal));
    
    0 讨论(0)
提交回复
热议问题