PHP: Parse string ["key", "value"] into associative array -


how can parse string of following format associative array?

[ ["key1", "value1"], ["key2", "value2"], ["key3", "value3] ] 

into:

array (     ["key1"] => "value1"     ["key2"] => "value2"     ["key3"] => "value3" ) 

thanks!

edit: data in string format i.e:

$stringdata ='[ ["key1", "value1"], ["key2", "value2"], ["key3", "value3"] ]'; 

use loop , loop through whole array , assign values new array using first element key , second element value. this:

$new_array = array(); foreach($array $arr) {     $new_array[$arr[0]] = $arr[1]; } 

but parse string array take following regex approach , loop:

$str = '[ ["key1", "value1"], ["key2", "value2"], ["key3", "value3"] ]'; preg_match_all('/(\[("(.*?)"), ("(.*?)")\])/i', $str, $matches); //now have in $matches[3] , $matches[5] keys , values //and turn array using loop  $new_array = array(); for($k = 0; $k < count($matches[3]); $k++) {     $new_array[$matches[3][$k]] = $matches[5][$k]; } 

see live demo https://3v4l.org/u3jpl


Comments