Adding an item to an associative array

//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 does not work as it replaces the value of the data. How can I add this associative value for each loop? $file_data - an array of data with dynamic size.

+51
php
Mar 21 '11 at 23:11
source share
5 answers

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

Or if you need an array that maps categories to an 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); 
+66
Mar 21 '11 at 23:13
source share

You can just do it

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

If you are working on php 5.4 +

 $data += [$category => $question]; //here was incorrect bracket 
+38
Sep 08 '14 at 5:52
source share

before the loop:

 $data = array(); 

then in your loop:

 $data[] = array($catagory => $question); 
+19
Mar 21 '11 at 23:12
source share

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

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

This will push array to the end of the current array . Or, if you are just trying to add individual values ​​to the end of your array, no more arrays, you can use this:

 array_push($data,$question); 
+1
Jun 29 '17 at 15:54 on
source share

For those who also need to add an associative array to 2d, you can also use the answer above and use code like this

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

you can call it (to check the result:

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

which should print $ question

0
Dec 19 '17 at 7:34 on
source share



All Articles