如何从 PHP 中的字符串创建关联数组?

How to make an associative array from a string in PHP?

假设现在我有一个字符串:

$detail = "1=>Apple, 2=>Cheesecake, 3=>Banana";

如何将字符串 $detail 转换或解析为关联数组并变成这样:

$detail_arr['1'] = "Apple";
$detail_arr['2'] = "Cheesecake";
$detail_arr['3'] = "Banana";

喜欢下面的代码:

$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, ...

使用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]);