-2

I want little help about php, my English knowledge is not good i will explain my problem as well.

on my database have this kind of field,

Answers["1=>4,2=>5,3=>3,4=>1"];

so friends i want to get this answers to my associative array like this

$answers = array([1]=>4,[2]=>5,[3]=>3,[4]=>1);

please help me!

Sathiamoorthy
  • 8,831
  • 9
  • 65
  • 77
  • 1
    Don't store multiple values in a single database field. If you have a table of (num, value) and 4 rows this becomes significantly easier. – danblack Oct 23 '20 at 05:16

2 Answers2

1

This can be a way to resolve

$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
)
Priya
  • 1,522
  • 1
  • 14
  • 31
0
  • First explode them using , .
  • Then loop through them to assign it to array after exploding by =>.
$a = '1=>4,2=>5,3=>3,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
)
Dark Knight
  • 6,116
  • 1
  • 15
  • 37