php 将项目添加到关联数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5384847/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 21:13:43  来源:igfitidea点击:

Adding an item to an associative array

php

提问by Phil

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

}

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

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

回答by Mohyaddin Alaoddin

You can simply do this

你可以简单地做到这一点

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

If your're running on php 5.4+

如果您在 php 5.4+ 上运行

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

回答by ThiefMaster

I think you want $data[$category] = $question;

我想你想要 $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);

回答by moe

before for loop :

在 for 循环之前:

$data = array();

then in your loop:

然后在你的循环中:

$data[] = array($catagory => $question);

回答by Mike

I know this is an old question but you can use:

我知道这是一个老问题,但您可以使用:

array_push($data, array($category => $question));

This will push the arrayonto the end of your current array. Or if you are just trying to add single values to the end of your array, not more arrays then you can use this:

这会将 推array到当前array. 或者,如果您只是想将单个值添加到数组的末尾,而不是更多的数组,那么您可以使用:

array_push($data,$question);

回答by maximran

For anyone that also need to add into 2d associative array, you can also use answer given above, and use the code like this

对于还需要添加到二维关联数组中的任何人,您也可以使用上面给出的答案,并使用这样的代码

 $data[$category]["test"] = $question

you can then call it (to test out the result by:

然后你可以调用它(通过以下方式测试结果:

echo $data[$category]["test"];

which should print $question

应该打印 $question