将平面数组的管道分隔值拆分为关联数组
//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
是一个具有动态大小的数据数组。
//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_data
is an array of data that has a dynamic size.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
你可以简单地这样做
如果你运行的是 php 5.4+,
You can simply do this
If your're running on php 5.4+
我认为您想要
$data[$category] = $question;
或者如果您想要一个将类别映射到问题数组的数组:
I think you want
$data[$category] = $question;
Or in case you want an array that maps categories to array of questions:
在 for 循环之前:
然后在循环中:
Before for loop:
Then in your loop:
我知道这是一个老问题,但您可以使用:
这会将
array
推到当前array
的末尾。或者,如果您只是尝试将单个值添加到数组的末尾,而不是更多数组,那么您可以使用以下命令:I know this is an old question but you can use:
This will push the
array
onto the end of your currentarray
. Or if you are just trying to add single values to the end of your array, not more arrays then you can use this:对于还需要添加到二维关联数组中的任何人,您还可以使用上面给出的答案,并使用这样的代码,
然后您可以调用它(通过以下方式测试结果:
which should print $question
For anyone that also need to add into 2d associative array, you can also use answer given above, and use the code like this
you can then call it (to test out the result by:
which should print $question
要将管道分隔值数组拆分为关联数组,请循环数据,在管道上分解,然后使用数组解构语法声明键变量,然后将管道后值推送到具有定义键的结果数组中。
代码:(演示)
输出:
To split your array of pipe-delimited values into an associative array, loop over the data, explode on pipes, then use array destructuring syntax to declare the key variable, then push the post-pipe value into the result array with the defined key.
Code: (Demo)
Output: