PHP Array to Json Object

后端 未结 6 1085
鱼传尺愫
鱼传尺愫 2020-12-09 10:28

I need to convert a PHP array to json but I don\'t get what I expect. I want it to be an object that i can navigate easily with numeric index. Here\'s an example code:

相关标签:
6条回答
  • 2020-12-09 11:06

    You want to json_encode($json, JSON_FORCE_OBJECT).

    The JSON_FORCE_OBJECT flag, as the name implies, forces the json output to be an object, even when it otherwise would normally be represented as an array.

    You can also eliminate the use of array_push for some slightly cleaner code:

    $json[] = ['ip' => $ip, 'port' => $port];
    
    0 讨论(0)
  • 2020-12-09 11:06

    To get array with objects you can create stdClass() instead of array for inner items like below;

    <?PHP
    
        $json = array();
        $itemObject = new stdClass();
        $itemObject->ip = "192.168.0.1";
        $itemObject->port = 2016;
    
        array_push($json, $itemObject);
        $json = json_encode($json, JSON_PRETTY_PRINT);
        echo $json;
    
    ?>
    

    A working example http://ideone.com/1QUOm6

    0 讨论(0)
  • 2020-12-09 11:11

    just use only

    $response=array();
    $response["0"]=array("ip"     => "192.168.0.1",
                         "port"   => "2016");
    $json=json_encode($response,JSON_FORCE_OBJECT);
    
    0 讨论(0)
  • In order to get an object and not just a json string try:

    $json = json_decode(json_encode($yourArray));
    

    If you want to jsonise the nested arrays as well do:

    $json =json_decode(json_encode($yourArray, JSON_FORCE_OBJECT));
    
    0 讨论(0)
  • 2020-12-09 11:17
    $ip   = "192.168.0.1";
    $port = "2016";
    $json = array("response" => array("ip" => $ip, "port" => $port)); 
    //IF U NEED AS JSON OBJECT
    $json = [array("ip" => $ip, "port" => $port)]; //IF U NEED AS JSON ARRAY
    $json = json_encode($json);
    echo $json;
    
    0 讨论(0)
  • 2020-12-09 11:24

    Just in case if you want to access your objectivitized json whole data OR a specific key value:

    PHP SIDE

     $json = json_encode($yourdata, JSON_FORCE_OBJECT);
    

    JS SIDE

     var json = <?=$json?>;
     console.log(json);            // {ip:"192.168.0.1", port:"2016"}
     console.log(json['ip']);      // 192.168.0.1
     console.log(json['port']);    // 2016
    
    0 讨论(0)
提交回复
热议问题