使用foreach向关联数组添加值?

Phi*_*hil 6 php foreach associative-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;

}
Run Code Online (Sandbox Code Playgroud)

会发生什么是assoc值不断被删除.有没有办法让值附加到数组?如果没有,我怎么能这样做?

Pas*_*TIN 8

您可以使用以下内容附加到$file_data_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;
}
Run Code Online (Sandbox Code Playgroud)

($item可以避免临时变量,$file_data_array在同一时间执行数组声明和效果)


有关更多信息,请查看本手册的以下部分:使用方括号语法创建/修改