将项添加到关联数组

2022-08-30 07:29:19
//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


答案 1

您只需执行此操作即可

$data += array($category => $question);

如果你运行的是 php 5.4+

$data += [$category => $question];

答案 2

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

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

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