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.

2
  • 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. Commented Mar 9, 2012 at 0:38
  • Edited the question. Sorry. I'm more concerned with the array itself than what's stored inside the index at the bottom level. Commented Mar 9, 2012 at 0:44

3 Answers 3

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?

Sign up to request clarification or add additional context in comments.

2 Comments

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.
@Exp please add an educational explanation to this answer when you have time.
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);

1 Comment

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.
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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.