PHP - 从分隔的字符串创建多维关联数组

Can you turn this string:

"package.deal.category"

Into an array like this:

$array['package']['deal']['category']

The value inside the index at this point can be anything.

What have you tried? The absolute answer to this is very easy:

$keys = explode('.', $string);
$array = array();
$arr = &$array;
foreach ($keys as $key) {
   $arr[$key] = array();
   $arr = &$arr[$key];
}
unset($arr);

...but why would this be useful to you?

I don't really understand, what the problem is with this?

$parts = explode('.', $string);
$array = array();

while (!empty($parts)) {
    $array = array(array_pop($parts) => $array);
}

Try this:

$text = 'package.deal.category';

$array = array();
foreach(array_reverse(explode('.', $text)) as $key) $array = array($key => $array);

print_r($array);

I know this was asked some time ago, but for anyone else looking for another possible answer that doesn't involve loops, try using JSON.

To make $array['key1']['key2'] = $value

$key = 'Key1.Key2';
$delimiter = '.';
$value = 'Can be a string or an array.';

$jsonkey = '{"'.str_replace($delimiter, '":{"', $key).'":';
$jsonend = str_repeat('}', substr_count($jsonkey, '{'));
$jsonvalue = json_encode($value);
$array = json_decode($jsonkey.$jsonvalue.$jsonend, true);