Convert key/value string into associative array

孤街醉人 提交于 2021-02-05 08:09:13

问题


As an example, my string might look like this:

first_name:Tom last_name:Jones email:tom@somedomain.com

I would want my array to look like the following:

Array (
  ['first_name'] => 'Tom',
  ['last_name'] => 'Jones',
  ['email'] => 'tom@somedomain.com'
)

This will then be used to search the database based on the column and value. So I will first need to retrieve the key (such as first_name) and the value (like Tom) for searching.

I have the following regex:

((?:[a-z][a-z0-9_]*))

This works. It finds all strings before : and after :, but I cannot figure out how to parse this to put it in an array of the format I need.


回答1:


You can just explode() your string first on a space and then with array_map() each value on a colon. After that just use array_column() to get the keys and values into place:

$result = array_column(array_map(function($v){
    return explode(":", $v);
}, explode(" ", $str)), 1, 0);

You can also do it with a regex as you started and use named capturing groups, e.g.

preg_match_all("/(?P<keys>\w+):(?P<values>[\w@]+)/", $str, $m);
$result = array_combine($m["keys"], $m["values"]);



回答2:


The above method works but is overly hard to read in my opinion. You can much more easily and efficiently do this with the following method no need to make three extra function calls.

$user_info = 'first_name:Tom last_name:Jones email:tom@somedomain.com';

$user = array();
foreach (explode(' ', $user_info) as $property) {
    $part = explode(':', $property);
    $user[$part[0]] = $part[1];
}


来源:https://stackoverflow.com/questions/36368130/convert-key-value-string-into-associative-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!