【问题标题】:How to make an associative array from a string in PHP?如何从 PHP 中的字符串创建关联数组?
【发布时间】:2019-04-20 21:47:08
【问题描述】:

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

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

【问题讨论】:

  • 如果关键是价格,那么您的数组中只能有一个价格相同的商品。

标签: php arrays foreach associative-array


【解决方案1】:

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

【讨论】:

  • 这就是答案!感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-13
  • 2011-06-17
  • 1970-01-01
  • 2015-03-08
相关资源
最近更新 更多