将分隔的字符串解析为关联数组

时间:2021-06-29 22:07:43

I'm just optimising my code and if there is a function that does something like this, i can get rid of my own

我只是优化我的代码,如果有一个函数做这样的事情,我可以摆脱我自己的

There are duplicates for parsing query strings but the string I'm paring is in this format:

解析查询字符串有重复,但我正在使用的字符串采用以下格式:

$string = "cheese/camel/egg/cream";

is there a php function whereby I can parse this into an associative array?

是否有一个PHP函数,我可以将其解析成一个关联数组?

Lets say if I were to define the array with keys like:

让我们说如果我用以下键来定义数组:

$keys = array( "val1", "val2", "val3", "val4" );

is there a php function to parse the string into these variables? Something like:

是否有一个PHP函数来解析这些变量的字符串?就像是:

$associative_array = magic_function($keys, $string, $delimiter);

to end up with something like this:

最终得到这样的东西:

array(4) {
      "var1" => "cheese",
      "var2" => "camel",
      "var3" => "egg",
      "var4" => "cream"
}

1 个解决方案

#1


8  

PHP provides many simple functions, you just have to use them together:

PHP提供了许多简单的功能,你只需要一起使用它们:

$array = array_combine($keys, explode('/', $string));

Reference: array_combine, explode

参考:array_combine,explode

More array and string functions.

更多数组和字符串函数。

#1


8  

PHP provides many simple functions, you just have to use them together:

PHP提供了许多简单的功能,你只需要一起使用它们:

$array = array_combine($keys, explode('/', $string));

Reference: array_combine, explode

参考:array_combine,explode

More array and string functions.

更多数组和字符串函数。