3

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.

JayNCoke
  • 1,091
  • 2
  • 11
  • 17
  • 1
    Your question is a bit confusing. What should the value of `$array['package']['deal']['category']` be? You've defined an index to access, but not a value. – Horatio Alderaan Mar 09 '12 at 00:38
  • Edited the question. Sorry. I'm more concerned with the array itself than what's stored inside the index at the bottom level. – JayNCoke Mar 09 '12 at 00:44

3 Answers3

9

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?

hakre
  • 193,403
  • 52
  • 435
  • 836
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • Thanks, @tandu! I admit, I probably could have solved this if I had taken the time to look at the problem. I hardly ask questions on here unless I absolutely need to. After looking at your solution, I had one of those "of course, duh" moments. There's a use for it, but I'm sure that's a whole different discussion. – JayNCoke Mar 09 '12 at 01:14
  • @Exp please add an educational explanation to this answer when you have time. – mickmackusa Mar 24 '21 at 00:40
0

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);
Mick
  • 1
  • The problem with manually crafting a json string is that it may be unreliable (not to mention harder to follow the coding logic). I would not endorse this technique. – mickmackusa Mar 24 '21 at 00:37
0
$text = 'package.deal.category';

// convert 'package.deal.category' into ['package', 'deal', 'category']
$parts = explode('.', $text);

// changes ['package', 'deal', 'category'] into ['category', 'deal', 'package']
$revparts = array_reverse($parts);

// start with an empty array.
// in practice this should probably
// be the "value" you wish to store.
$array = [];

// iteratively wrap the given array in a new array
// starting with category, then wrap that in deal
// then wrap that in package
foreach($revparts as $key) $array = [$key => $array];

print_r($array);
Martin
  • 5,945
  • 7
  • 50
  • 77