Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 310
Phil Avatar asked Mar 21 '11 23:03

Phil


2 Answers

You can simply do this

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

If your're running on php 5.4+

$data += [$category => $question]; 
like image 91
Mohyaddin Alaoddin Avatar answered Oct 31 '22 14:10

Mohyaddin Alaoddin


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); 
like image 31
ThiefMaster Avatar answered Oct 31 '22 12:10

ThiefMaster