//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
5,8864 gold badges14 silver badges32 bronze badges
asked Mar 21, 2011 at 23:11
You can simply do this
$data += array[$category => $question];
If your're running on php 5.4+
$data += [$category => $question];
answered Sep 8, 2014 at 5:52
4
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,1317 gold badges29 silver badges47 bronze badges
answered Mar 21, 2011 at 23:13
ThiefMasterThiefMaster
302k78 gold badges581 silver badges625 bronze badges
2
Before for loop:
$data = array[];
Then in your loop:
$data[] = array[$catagory => $question];
Uwe Keim
38.7k56 gold badges173 silver badges282 bronze badges
answered Mar 21, 2011 at 23:12
moemoe
28.1k3 gold badges18 silver badges16 bronze badges
6
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,2241 gold badge19 silver badges35 bronze badges
answered Jun 29, 2017 at 15:54
MikeMike
1,7282 gold badges42 silver badges73 bronze badges
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
answered Dec 19, 2017 at 7:34
maximranmaximran
4054 silver badges11 bronze badges