将具有三个分隔符的字符串解析为索引数组的关联数组
我有这行字符串
Fruits-banana|apple|orange:Food-fries|sausages:Desserts-ice Cream|apple pie
:
(冒号)是分隔符主主题,|
是不同类型子主题的分隔符。
我尝试将其分解并放入数组中,我需要将结果显示在下拉菜单中:-
Fruits
banana
apple
orange
Food
fries
sausages
...
代码:
$result = explode(":", $data);
foreach ($result as $res) {
$sub_res[] = explode("-", $res);
}
foreach ($sub_res as $sub) {
//echo $sub[1] . "<br>";
\*
Over here, I can get the strings of
[0] => banana|apple|orange,
[1] => sausages|fries,
*/
// I explode it again to get each items
$items[] = explode("|", $sub[1]);
$mainCategory[] = $sub[0]; // This is ([0]=>Fruits, ]1]=>Food, [2]=>dessert
// How do I assign the $items into respective categories?
}
I have this line of string
Fruits-banana|apple|orange:Food-fries|sausages:Desserts-ice cream|apple pie
the :
(colon) is the separator for the main topic, and the |
is the separator for the different type of sub topics.
I tried to explode it out and put it into array, I need the result to be something like this to be displayed in a drop down menu:-
Fruits
banana
apple
orange
Food
fries
sausages
...
Code:
$result = explode(":", $data);
foreach ($result as $res) {
$sub_res[] = explode("-", $res);
}
foreach ($sub_res as $sub) {
//echo $sub[1] . "<br>";
\*
Over here, I can get the strings of
[0] => banana|apple|orange,
[1] => sausages|fries,
*/
// I explode it again to get each items
$items[] = explode("|", $sub[1]);
$mainCategory[] = $sub[0]; // This is ([0]=>Fruits, ]1]=>Food, [2]=>dessert
// How do I assign the $items into respective categories?
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以执行以下操作:
工作链接
You can do:
Working link
代码:
更新以反映下拉列表的添加。看起来我刚刚做了你的作业,不过我将让你将所有内容合并到一个 foreach 循环中。
Code:
Updated to reflect the drop-down addition. Looks like I just did your homework, though I'll leave it up to you to combine all the into one foreach loop.
我建议 Codeaddicts 的 答案
I'd propose an arguably more readable version of codeaddicts' answer