0

I have a string (in PHP) representing a JS array, and for testing purpose would like to convert it to a PHP array to feed them into a unit test. Here's an example string

{ name: 'unique_name',fof: -1,range: '1',aoe: ',0,0,fp: '99,desc: 'testing ability,image: 'dummy.jpg'}

I could use a explode on the "," then on the colon, but that is rather inelegant. Is there a better way?

Extrakun
  • 19,057
  • 21
  • 82
  • 129
  • This is not valid json. `json_decode()` will not work. Before considering testing, spend time correcting the json payload syntax. – mickmackusa Mar 23 '22 at 06:55

3 Answers3

4
$php_object = json_decode($javascript_array_string)

This will return an object, with properties corresponding to the javascript array's properties. If you want an associative array, pass true as a second parameter to json_decode

$php_array = json_decode($javascript_array_string, true)

There is also a json_encode function for going the other way.

Macha
  • 14,366
  • 14
  • 57
  • 69
1

You are looking for json_decode().

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
0

json_decode

<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));
var_dump(json_decode($json, true));

?> 

The above example will output:

object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}
Haim Evgi
  • 123,187
  • 45
  • 217
  • 223