spreaderman
spreaderman

Reputation: 1088

Codeigniter / PHP/ convert Object to JSON

I cannot fully understand what I have below and I need to convert it to JSON.

My guess is I have an array of 16 starting from 0 to 15. Item 0 is an object by ["id"]=>"1", ["ip_address"]=>"127.0.0.3", etc looks like an associative array. Confused.

Second question when I decode($abovearray) I get something but doesn't look like JSON! Any help much appreciated.

Here is a sample of my array output that I need to convert to JSON.

array(16) {
           [0]=> object(stdClass)#31 (25) {
              ["id"]=> string(1) "1"
              ["ip_address"]=> string(9) "127.0.0.3"
              ["username"]=> string(13) "administrator"
              [~snip~]
              }
           [1]=> object(stdClass)#33 (25) {
              ["id"]=> string(1) "2"
              ["ip_address"]=> string(15) "111.111.111.201"
              ["username"]=> string(0) ""
              [~snip~]
              }
     ...}

Upvotes: 0

Views: 2341

Answers (3)

Przemek eS
Przemek eS

Reputation: 1304

It look like data in view for js but in php use this in PHP

  $jsonEncode  =  json_encode($array);

in JS How to decode a JSON string?

Upvotes: 0

user4419336
user4419336

Reputation:

On controller

public function test() {
    $data = array();

    $data[] = array(
        'id' => '1',
        'ip_address' => "127.0.0.3",
        'username' => 'administrator'
    );

    $data[] = array(
        'id' => '2',
        'ip_address' => "111.111.111.201",
        'username' => ''
    );

    echo json_encode($data);
}

Should out put

[{"id":"1","ip_address":"127.0.0.3","username":"administrator"},{"id":"2","ip_address":"111.111.111.201","username":""}]

<script type="text/javascript">
$('#commit').click(function(e){
    e.preventDefault();
    $.ajax
    ({ 
    type: 'get',
    url: "<?php echo base_url('welcome/test');?>",
    dataType: 'json',
    success: function(response)
    {
       alert(response['username']) // you may need to use the jquery each function

      https://api.jquery.com/each/

    });
});
</script>

Upvotes: 0

Hikmat Sijapati
Hikmat Sijapati

Reputation: 6994

Try like this...

$json = json_encode($array,JSON_FORCE_OBJECT);
echo $json;

Upvotes: 1

Related Questions