问题描述
我几乎不需要有关PHP的帮助,我的英语知识不好,我也会解释我的问题。
在我的数据库上有这样的字段
Answers["1=>4,2=>5,3=>3,4=>1"];
所以朋友,我想这样获得我的关联数组的答案
$answers = array([1]=>4,[2]=>5,[3]=>3,[4]=>1);
请帮助我!
解决方法
这可能是解决的方法
$a = "1=>4,2=>5,3=>3,4=>1";
$a = "{" . preg_replace("/(\d+)=>/",'"${1}":',$a) . "}";
$output = json_decode($a,true);
// output
Array
(
[1] => 4
[2] => 5
[3] => 3
[4] => 1
)
,
- 首先使用
,
炸开它们。 - 然后循环遍历它们,以
=>
爆炸后将其分配给数组。
$a = '1=>4,4=>1';
$final = [];
foreach(explode(',',$a) as $value){
list($key,$val) = explode('=>',$value);
$final[$key] = $val;
}
echo '<pre>'; print_r($final);
Output:
Array
(
[1] => 4
[2] => 5
[3] => 3
[4] => 1
)