假设现在我有一个字符串:
$detail = "1=>Apple, 2=>Cheesecake, 3=>Banana";
如何将字符串$detail
转换或解析为关联数组,并变成这样:
$detail_arr['1'] = "Apple";
$detail_arr['2'] = "Cheesecake";
$detail_arr['3'] = "Banana";
OR
类似于下面的代码:
$detail_arr = array("1"=>"Apple", "2"=>"Cheesecake", "3"=>"Banana");
foreach($detail_arr as $x=> $x_name)
{
echo "Price=" . $x . ", Name=" . $x_name;
}
,并显示:
Price = 1, Name = Apple, ...
答案 0 :(得分:3)
使用explode()
通过,
分隔符转换为字符串并遍历结果
$arr = [];
foreach (explode(',', $detail) as $item){
$parts = explode('=>', $item);
$arr[trim($parts[0])] = $parts[1];
}
在demo中查看结果
您也可以使用preg_match_all()
和array_combine()
来完成这项工作。
preg_match_all("/(\d+)=>([^,]+)/", $detail, $matches);
$arr = array_combine($matches[1], $matches[2]);