gpt4 book ai didi

php - 在php中将字符串转换为数组

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:05:31 25 4
gpt4 key购买 nike

我有如下字符串

["Day1"]["Morning"]=mutton&["Day1"]["Evening"]=Juice&["Day2"]["Morning"]=burger&["Day2"]["Evening"]=pizza 

我正在尝试将其转换为如下所示的数组

$arr["Day1"]["Morning"] = "mutton";
$arr["Day1"]["Evening"] = "Juice";
$arr["Day2"]["morning"] = "burger";
$arr["Day2"]["evening"] = "pizza";

我试过类似下面的东西。

$str = '["Day1"]["Morning"]=mutton&["Day1"]["Evening"]=Juice&["Day2"]["Morning"]=burger&["Day2"]["Evening"]=pizza';
$pieces = explode("&", $str);

foreach($pieces as $pie)
{
$arr.$pie;
}
var_dump($arr);

我知道上面的代码真的很蠢:/。有什么合适的解决方案吗?

最佳答案

你可以这样做......

<?php
$str='["Day1"]["Morning"]=mutton&["Day1"]["Evening"]=Juice&["Day2"]["Morning"]=burger&["Day2"]["Evening"]=pizza';
$arr = explode('&',$str);
foreach($arr as $v)
{
$valarr=explode('=',$v);
preg_match_all('/"(.*?)"/', $valarr[0], $matches);
$narr[$matches[1][0]][$matches[1][1]]=$valarr[1];
}

print_r($narr);

输出:

Array
(
[Day1] => Array
(
[Morning] => mutton
[Evening] => Juice
)

[Day2] => Array
(
[Morning] => burger
[Evening] => pizza
)

)

你可以像 echo $arr["Day1"]["Morning"] 这样打印 mutton

Demo

关于php - 在php中将字符串转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21746826/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com