将项目添加到关联数组 [英] Adding an item to an associative array

查看:34
本文介绍了将项目添加到关联数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

//go through each question
foreach($file_data as $value) {
   //separate the string by pipes and place in variables
   list($category, $question) = explode('|', $value);

   //place in assoc array
   $data = array($category => $question);
   print_r($data);

}

这不起作用,因为它替换了数据的值.我怎样才能让它在每个循环中添加一个关联值?$file_data 是一个具有动态大小的数据数组.

This is not working as it replaces the value of data. How can I have it add an associative value each loop though? $file_data is an array of data that has a dynamic size.

推荐答案

我想你想要 $data[$category] ​​= $question;

或者,如果您想要一个将类别映射到问题数组的数组:

Or in case you want an array that maps categories to array of questions:

$data = array();
foreach($file_data as $value) {
    list($category, $question) = explode('|', $value, 2);

    if(!isset($data[$category])) {
        $data[$category] = array();
    }
    $data[$category][] = $question;
}
print_r($data);

这篇关于将项目添加到关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆