Convert javascript string to php array

I clean the site using php to get some data. The data I receive is a valid javascript array.

"['v42, 2015', 23428, 30243, 76993] , ['v43, 2015', 24060, 30401, 73412] , ['v44, 2015', 22855, 29720, 71573] , ['v45, 2015', 24455, 30757, 78991] , ['v46, 2015', 24275, 30398, 84424]" 

Now I have this line in php, but how can I convert it to a php array?

+6
source share
3 answers
 $string = "['v42, 2015', 23428, 30243, 76993] , ['v43, 2015', 24060, 30401, 73412] , ['v44, 2015', 22855, 29720, 71573] , ['v45, 2015', 24455, 30757, 78991] , ['v46, 2015', 24275, 30398, 84424]"; 

This is a valid js array if you add the correct separator between square and trailing square brackets. In addition, to meet the requirements of php json parser, line separators must have double quotes instead of single-quotes, so you need to perform a quick change.

Then you can decode it like this:

 $ary = json_decode('['.str_replace("'",'"',$string).']', true); 
+6
source

Single quotes may be valid in JS, but JSON sometimes has problems with it. You can try it here: JSONLint

To get a valid JSON, just replace the single quotes ' with double quotes " to get an array with arrays, you have to surround your string with brackets [] .

Try this sample code:

 $string = "['v42, 2015', 23428, 30243, 76993] , ['v43, 2015', 24060, 30401, 73412] , ['v44, 2015', 22855, 29720, 71573] , ['v45, 2015', 24455, 30757, 78991] , ['v46, 2015', 24275, 30398, 84424]"; $string = str_replace( "'" , '"', $string ); $string = '['.$string.']'; echo "<pre>"; var_dump( json_decode( $string ) ); 
+2
source

You can try replacing [ ] with '' and then break the string.

 $string = str_replace(']', '', str_replace('[', '',$string)); $array = explode(',', $string); 
0
source

All Articles