Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/229.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 将字符串转换为数组或以特定字符串为键的多维数组_Php - Fatal编程技术网

Php 将字符串转换为数组或以特定字符串为键的多维数组

Php 将字符串转换为数组或以特定字符串为键的多维数组,php,Php,我想将字符串转换成多维数组,以便在无序列表中显示它 conditions 1. .... 2..... what to bring 1.... 2.... Inurance 1.. 2... $notes变量的内容: Conditions: Adult fares apply from 13 years old and above.

我想将字符串转换成多维数组,以便在无序列表中显示它

     conditions
          1. ....
          2.....
     what to bring
           1....
           2....
     Inurance
           1..
           2...
$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函数

   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...
请注意,键(条件、要带来的内容..)是动态名称,因此它可能会不时更改,但格式是相同的


有什么建议吗?

您可以通过
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>";

您需要将字符串作为文本而不是图像发布。张贴所需输出的样本,并且总是对有文本图片的问题进行向下投票。