Search code examples
phpjsonmultidimensional-arrayconverters

Generate json string from multidimensional array data


I am using a plugin that requires an array of associative rows as a json formatted string -- something like:

[
    {oV: 'myfirstvalue', oT: 'myfirsttext'},
    {oV: 'mysecondvalue', oT: 'mysecondtext'}
]

How do I convert my multidimensional array to valid JSON output using PHP?


Solution

  • The simplest way would probably be to start with an associative array of the pairs you want:

    $data = array("myfirstvalue" => "myfirsttext", "mysecondvalue" => "mysecondtext");
    

    then use a foreach and some string concatenation:

    $jsontext = "[";
    foreach($data as $key => $value) {
        $jsontext .= "{oV: '".addslashes($key)."', oT: '".addslashes($value)."'},";
    }
    $jsontext = substr_replace($jsontext, '', -1); // to get rid of extra comma
    $jsontext .= "]";
    

    Or if you have a recent version of PHP, you can use the json encoding functions built in - just be careful what data you pass them to make it match the expected format.