Skip to content
Advertisement

PHP convert similar names variables to json

I’m getting via url querystring variables like:

myserver_state=1&myserver_running=2&myserver_mem=3

Currently i’m adding to an existing json like:

{
   "key1": "1",
   "key2": "2",
   "key3": "3",
   "myserver_state": "1",
   "myserver_running": "2",
   "myserver_mem": "3"
}

And i really want it like this:

{
   "key1": "1",
   "key2": "2",
   "key3": "3",
   "myserver": {
      "state": "1",
      "running": "2",
      "mem": "3"
   }
}

I’m using this to load them:

        $formdata = array(
          'state'=> $_POST['state'],
          'uassip'=> $_POST['uassip'],
          'uassipport'=> $_POST['uassipport'],
          'c_uacminrtpport'=> $_POST['c_uacminrtpport'],
          'c_uacmaxrtpport'=> $_POST['c_uacmaxrtpport'],
          'c_cps'=> $_POST['c_cps'],
          'c_totalcalls'=> $_POST['c_totalcalls'],
          'c_maxchannels'=> $_POST['c_maxchannels'],
          'c_duration'=> $_POST['c_duration'],
          'c_to'=> $_POST['c_to'],
          'c_uacxml'=> $_POST['c_uacxml']
        );

        echo "fromdata: <br>"; echo var_dump($formdata) .  "<br><hr>";
        if(file_put_contents('testconfig.json', json_encode($formdata) )) echo 'OK';
        else echo 'Unable to save data in "testconfig.json"';


Many thanks!

EDIT:

following comments i tried:

status.php?server1[current_state]=10

this actually works to:

    "c_uacxml": "telnyx-uac-invite-ok.xml",
    "server1": {
        "current_state": "10"
    }
}

Which is great, BUT, if i then want to add an element like this: status.php?server1[current_mem]=1

This actually REPLACES the whole server1

    "c_uacxml": "telnyx-uac-invite-ok.xml",
    "server1": {
        "current_mem": "10"
    }
}

and i lose the already existing current_state

Advertisement

Answer

Just use multidimensional array within your URL like:

test.php?key1=1&key2=2&myserver[state]=1&myserver[running]=2&myserver[mem]=3

so easy script

<?php
echo '<pre>';
echo json_encode($_GET, JSON_PRETTY_PRINT);

will give you

{
    "key1": "1",
    "key2": "2",
    "myserver": {
        "state": "1",
        "running": "2",
        "mem": "3"
    }
}

of course, if required you can use also POST request with the same naming rules.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement