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

8
解决方案已找到并得到投票。
以下是我的代码:
//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;

}

发生的情况是 assoc 值不断被擦除。有没有办法让值附加到数组中?如果不能,我还能用什么其他方法实现这个功能?


前15分钟不让我发表评论,我的评论有点过早了…… - Phil
4个回答

9
你可以像这样将内容追加到$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 的结尾处)


要获取更多信息,请查看手册的以下部分:用方括号语法创建/修改数组


这是一个非常干净的解决方案。我会投票支持它,而不是我的解决方案。 =D - Ryre

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

}

完美运行,但是排名第二 :/ - Phil

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

我仍然可以使用$file_data_array['title']来接收这个值吗? - Phil
不行。但是以那种方式访问数据是问题的一部分。你可以使用$file_data_array[0]['title']来访问第一个,$file_data_array[1]['title']来访问第二个,以此类推。 - Ryre

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


我不喜欢将所有标题存储在一起,而是希望将标题、内容和发布日期存储在同一个键下。这只是个人偏好。 - Ryre

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接