我想将字符串转换为多维数组,以便我可以在无序列表中显示它
$ notes变量的内容:
Conditions:
Adult fares apply from 13 years old and above. Child fares apply from 4 to
12 years old
Infants not included
What to bring:
Sunscreen, water bottle, hat, sunglasses, camera, small 7kg overnight bag
if using the hop on hop off option
What to wear:
Warm clothes, windbreaker, comfortable walking shoes
Insurance:
We highly recommend all passengers have travel insurance coverage
Optional extras paid on arrival:
Helicopter joy flight over the 12 Apostles AUD145
Not included:
Dinner (at own expen
想要像这样的输出
[
'conditions => ['some','some'],
'what to bring' => ['content','content']
.......
]
到目前为止我尝试使用爆炸功能
explode(',',$notes)
但这是我不想要的输出
array:8 [
0 => """
Conditions:\n
Adults fares ....
\n
What to bring
.....
1 => "water bottle"
2 => "hat"
......
]
因此预期输出为无序列表
conditions
1. ....
2.....
what to bring
1....
2....
Inurance
1..
2...
请注意,键(条件,带来的内容......)是动态名称,因此它可能会不时更改,但格式相同
有什么建议吗?
答案 0 :(得分:1)
您可以按EOL
分解字符串,循环遍历数组并检查字符串是否以:
结尾,如果是,则将其用作密钥。
$notes = ''; //Your string here
//Init variables
$final = array();
$tempKey = "";
//Convert the string into an array
$arr = array_filter(explode(PHP_EOL, $notes), 'trim');
//Loop thru the array
foreach($arr as $val) {
if ( substr(trim($val), -1) === ':' ) $tempKey = rtrim(trim($val),":");
else $final[ $tempKey ][] = trim($val);
}
echo "<pre>";
print_r( $final );
echo "</pre>";
这将导致:
Array
(
[Conditions] => Array
(
[0] => Adult fares apply from 13 years old and above. Child fares apply from 4 to
[1] => 12 years old
[2] => Infants not included
)
[What to bring] => Array
(
[0] => Sunscreen, water bottle, hat, sunglasses, camera, small 7kg overnight bag
[1] => if using the hop on hop off option
)
[What to wear] => Array
(
[0] => Warm clothes, windbreaker, comfortable walking shoes
)
[Insurance] => Array
(
[0] => We highly recommend all passengers have travel insurance coverage
)
[Optional extras paid on arrival] => Array
(
[0] => Helicopter joy flight over the 12 Apostles AUD145
)
[Not included] => Array
(
[0] => Dinner (at own expen
)
)