将等号 (=) 转换为分隔值到 PHP 中的键和对
Convert Equals (=) to separated value to key and pair in PHP
我有这样的数据
1 = Answer1<br />
2 = Answer2<br />
3 = Answer3<br />
4 = Answer4<br />
5 = Answer5<br />
6 = Answer6<br />
7 = Answer7<br />
8 = Answer8<br />
9 = Answer9<br />
10 = Answer10<br />
11 = Answer11<br />
12 = Answer12<br />
13 = Answer13<br />
14 = Answer14<br />
15 = Answer15<br />
16 = Answer16<br />
17 = Answer17<br />
18 = Answer18<br />
19 = Answer19<br />
20 = Answer20<br />
21 = Answer21<br />
22 = Answer22<br />
23 = Answer23<br />
24 = Answer24<br />
25-26 = Answer25,Answer26<br />
27 = Answer27<br />
28-29 = Answer28,Answer29
以上是变量$lines的值。由于答案可以在数组中出现,我在使用像 $lines = explode( "\r\n", $lines );
.
这样的爆炸时得到了 27 个键
我的预期答案是在 =
之前有数字和在 =
之后有值的数组,如果答案是逗号分隔的,我希望它像下面这样,
28-29 => array('Answer28', 'Answer29');
如何使用 PHP 实现该目标?
在每一行使用 foreach()
尝试 explode()
https://www.php.net/manual/en/function.explode.php
$lines = explode("<br />\r\n", $lines);
$result = [];
foreach ($lines as $line) {
[$k, $v] = explode(" = ", $line);
$result[$k] = explode(",", $v);
}
print_r($result);
我有这样的数据
1 = Answer1<br />
2 = Answer2<br />
3 = Answer3<br />
4 = Answer4<br />
5 = Answer5<br />
6 = Answer6<br />
7 = Answer7<br />
8 = Answer8<br />
9 = Answer9<br />
10 = Answer10<br />
11 = Answer11<br />
12 = Answer12<br />
13 = Answer13<br />
14 = Answer14<br />
15 = Answer15<br />
16 = Answer16<br />
17 = Answer17<br />
18 = Answer18<br />
19 = Answer19<br />
20 = Answer20<br />
21 = Answer21<br />
22 = Answer22<br />
23 = Answer23<br />
24 = Answer24<br />
25-26 = Answer25,Answer26<br />
27 = Answer27<br />
28-29 = Answer28,Answer29
以上是变量$lines的值。由于答案可以在数组中出现,我在使用像 $lines = explode( "\r\n", $lines );
.
我的预期答案是在 =
之前有数字和在 =
之后有值的数组,如果答案是逗号分隔的,我希望它像下面这样,
28-29 => array('Answer28', 'Answer29');
如何使用 PHP 实现该目标?
在每一行使用 foreach()
explode()
https://www.php.net/manual/en/function.explode.php
$lines = explode("<br />\r\n", $lines);
$result = [];
foreach ($lines as $line) {
[$k, $v] = explode(" = ", $line);
$result[$k] = explode(",", $v);
}
print_r($result);