Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding a value to an associative array with a foreach?

Solution Found and voted on


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 the assoc values keep getting erased. Is there a way I can have the value append to array? If not, how else could I do this?

like image 462
Phil Avatar asked Mar 30 '11 22:03

Phil


2 Answers

You could append to the $file_data_array array using something like this :

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 $item variable could be avoided, doing the declaration of the array and the affectation at the end of $file_data_array at the same time)


For more informations, take a look at the following section of the manual : Creating/modifying with square bracket syntax

like image 121
Pascal MARTIN Avatar answered Oct 31 '22 05:10

Pascal MARTIN


Do you want to append associative arrays to $file_data_array?

If so:

//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,
    );

}
like image 37
bpierre Avatar answered Oct 31 '22 05:10

bpierre