2

I have email template data and I'm trying to get it as associative array with keys and labels. But I can't make proper array as it should be. My template is the following:

key_1:label1,key2:label2,...

I get this text from database in this way:

$subject = explode(',', $subject);
  foreach($subject as $s)
  {
    $subjects[] = explode(':', $s);
  }
var_dump($subjects);

And I'm getting array with this structure:

array(2) {
  [0]=>
  array(2) {
    [0]=>
    string(12) "key1"
    [1]=>
    string(16) "label1"
  }
  [1]=>
  array(2) {
    [0]=>
    string(12) "key2"
    [1]=>
    string(12) "label2"
  }
}

How to make array with keys ->key1, key2 and values -> label1, label2? Thanks!

ivva
  • 2,819
  • 9
  • 31
  • 64

1 Answers1

5

Try this:

$subject = explode(',', $subject);
foreach($subject as $s)
{
 $key_value = explode(':', $s);
 $subjects[$key_value[0]] = $key_value[1];
}
var_dump($subjects);

As you see here exploding the $s variable with ':' will give you 'key1','label1' and so on. Than you just need to use it in other array for key and value while looping through.

Indrajit
  • 405
  • 4
  • 12
  • Thank you! It was difficult to me to format it properly! :) – ivva Apr 09 '16 at 06:27
  • While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations! – Rizier123 Apr 09 '16 at 06:52