113
//go through each question
foreach($file_data as $value) {
   //separate the string by pipes and place in variables
   list($category, $question) = explode('|', $value);

   //place in assoc array
   $data = array($category => $question);
   print_r($data);

}

This is not working as it replaces the value of data. How can I have it add an associative value each loop though? $file_data is an array of data that has a dynamic size.

MaxiGui
  • 6,190
  • 4
  • 16
  • 33
Phil
  • 10,948
  • 17
  • 69
  • 101

5 Answers5

168

You can simply do this

$data += array($category => $question);

If your're running on php 5.4+

$data += [$category => $question];
Mohyaddin Alaoddin
  • 2,465
  • 1
  • 19
  • 14
111

I think you want $data[$category] = $question;

Or in case you want an array that maps categories to array of questions:

$data = array();
foreach($file_data as $value) {
    list($category, $question) = explode('|', $value, 2);

    if(!isset($data[$category])) {
        $data[$category] = array();
    }
    $data[$category][] = $question;
}
print_r($data);
webvitaly
  • 4,241
  • 8
  • 30
  • 48
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
35

Before for loop:

$data = array();

Then in your loop:

$data[] = array($catagory => $question);
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
moe
  • 28,814
  • 4
  • 19
  • 16
  • 2
    If you do it that way don't forget to init the array first by using $data = array(); or else php will throw a notice – Alex Bailey Mar 21 '11 at 23:14
  • I think SO caches my answer, as soo as posted it I realized I didnt see it being initialized in his code. So I added it and I saw your comment afterwards, thank you :-) – moe Mar 21 '11 at 23:15
  • 5
    This didn't work because it made an array inside the array. Sorry If my question kinda through you off. – Phil Mar 21 '11 at 23:27
  • PHP 5.4+ you can write a little less code: `$data=[];` `$data[] = [$category => $question];` – Justin Mar 20 '14 at 21:05
  • `$res = array(); $res[] = array('foo' => $bar); $foo = $res['foo'];` fails with **Undefined index: foo in..**, but below suggested plus sign works. – droid192 Jan 01 '17 at 21:09
  • 4
    this is adding to the array but as a seperate object – DragonFire Apr 11 '20 at 07:22
12

I know this is an old question but you can use:

array_push($data, array($category => $question));

This will push the array onto the end of your current array. Or if you are just trying to add single values to the end of your array, not more arrays then you can use this:

array_push($data,$question);
lasec0203
  • 2,422
  • 1
  • 21
  • 36
Mike
  • 1,853
  • 3
  • 45
  • 75
6

For anyone that also need to add into 2d associative array, you can also use answer given above, and use the code like this

 $data[$category]["test"] = $question

you can then call it (to test out the result by:

echo $data[$category]["test"];

which should print $question

maximran
  • 425
  • 4
  • 11