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

Php 使用foreach向关联数组添加值?,php,foreach,associative-array,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 inp

找到解决方案并投票表决


这是我的密码:

//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值不断被擦除。有没有办法将值附加到数组中?如果没有,我还能怎么做呢?

您需要一把额外的钥匙

//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 = 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' )
)
下面是它的一个演示:


您可以使用以下方法将
$file\u data\u数组
附加到数组中:

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\u data\u array
末尾声明数组和做作)



有关更多信息,请参阅手册的以下部分:

是否要将关联数组附加到
$file\u data\u 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,
    );

}

我仍然可以通过使用
$file\u data\u array['title']
来接收该值。不可以。但是以这种方式访问数据是问题的一部分。您可以使用
$file\u data\u array[0]['title']
访问第一个,使用
$file\u data\u array[1]['title']
访问第二个,等等。我不喜欢将所有标题存储在一起,而不是将标题、内容和发布日期存储在同一个键下。不过还是有点偏好。谢谢你,这就是我要找的!这是一个非常干净的解决方案。我会投票赞成我的解决方案=DWorks非常完美,但排名第二:/你必须接受正确的答案^ ^在前15分钟没有让我回答。我的评论有点先发制人。