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

时间:2011-03-30 22:10:23

标签: 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;

}

会发生的是,关键值会被删除。有没有办法让值附加到数组?如果没有,我怎么能这样做?

4 个答案:

答案 0 :(得分: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;
}

(可以避免使用临时$item变量,同时在$file_data_array末尾执行数组声明和效果


有关更多信息,请查看手册的以下部分:Creating/modifying with square bracket syntax

答案 1 :(得分:2)

是否要将关联数组附加到$file_data_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[] = array(
        "title" => $title,
        "content" => $content,
        "date_posted" => $date_posted,
    );

}

答案 2 :(得分:0)

你需要一把额外的钥匙。

//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++;
}    

答案 3 :(得分:0)

试试这个:

$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;

}

你最终的数组看起来像:

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

这是一个演示:

http://codepad.org/jdFabrzE