Adding a value to an associative array with foreach?

Solution found and voted


Here is my code:

//go through each question foreach($file_data as $value) { //separate the string by pipes and place in variables list($title, $content, $date_posted) = explode('|', $value); //create an associative array for each input $file_data_array['title'] = $title; $file_data_array['content'] = $content; $file_data_array['date_posted'] = $date_posted; } 

What happens is that member values ​​continue to fade. Is there a way I can add a value to an array? If not, how else can I do this?

+6
php foreach associative-array
source share
4 answers

You can add the following to the $file_data_array array:

 foreach($file_data as $value) { list($title, $content, $date_posted) = explode('|', $value); $item = array( 'title' => $title, 'content' => $content, 'date_posted' => $date_posted ); $file_data_array[] = $item; } 

(the temporary variable $item could be avoided by doing an array declaration and affectation at the end of $file_data_array at the same time)


See the next section of the manual for more information: Creating / Modifying Using Square Bracket Syntax p>

+7
source share

Do you want to add associative arrays to $file_data_array ?

If yes:

 //go through each question foreach($file_data as $value) { //separate the string by pipes and place in variables list($title, $content, $date_posted) = explode('|', $value); //create an associative array for each input $file_data_array[] = array( "title" => $title, "content" => $content, "date_posted" => $date_posted, ); } 
+1
source share

You need an additional key.

 //go through each question $x=0; foreach($file_data as $value) { //separate the string by pipes and place in variables list($title, $content, $date_posted) = explode('|', $value); //create an associative array for each input $file_data_array[$x]['title'] = $title; $file_data_array[$x]['content'] = $content; $file_data_array[$x]['date_posted'] = $date_posted; $x++; } 
0
source share

try the following:

 $file_data_array = array( 'title'=>array(), 'content'=>array(), 'date_posted'=>array() ); //go through each question foreach($file_data as $value) { //separate the string by pipes and place in variables list($title, $content, $date_posted) = explode('|', $value); //create an associative array for each input $file_data_array['title'][] = $title; $file_data_array['content'][] = $content; $file_data_array['date_posted'][] = $date_posted; } 

your last array will look something like this:

 $file_data_array = array( 'title' => array ( 't1', 't2' ), 'content' => array ( 'c1', 'c2' ), 'date_posted' => array ( 'dp1', 'dp2' ) ) 

here is a demonstration of this:

http://codepad.org/jdFabrzE

0
source share

All Articles