Search code examples
javascriptphparraysjsoneasyautocomplete

PHP Object array to javascript associative array


I have a PHP object array as follows:

array(223) {
  [0]=>
  object(stdClass)#5 (9) {
    ["id"]=>
    string(2) "10"
    ["name"]=>
    string(10) "Cyclops"
    ["address"]=>
    string(13) "GSDG"
  }
  [1]=>
  object(stdClass)#6 (9) {
    ["id"]=>
    string(2) "11"
    ["name"]=>
    string(11) "Professor X"
    ["address"]=>
    string(8) "XX"
  }

I need to convert it into a javascript array with the name and id in this format:

var characters = {
    data: [{
            "name": "Cyclops",
            id: 10
        },
        {
            "name": "Professor X",
            id: 11
        }
    ]
}

Here is what I have tried:

First I converted the PHP arrays to javascript objects and then used a for loop to push details of each array to a javascript object:

var js_data = <?php echo json_encode($chars) ?>;
var characters = [];

for (var i = 0; i < js_data.length; i++) {
    characters.push({
        data: js_data[i]
    })
}

But this results in an array of objects, each having a "data" property. Here is the console.log of testVariable:

0: {…}
​​​
data: Object { id: "10", name: "Cyclops", … }
​​​
__proto__: Object { … }
​​
1: {…}
​​​
data: Object { id: "11", name: "Professor X", … }

How do I fix this?


Solution

  • Isn't the hardest task, as you almost have your desired format. At first I have to add, that you possibly even not have to filter out the address field, as the plugin may ignore it completly. If this is the case, you could simply do this

    var characters = <?php json_encode(['data' => $chars]); ?>;
    

    And if you really need to filter out the address field, you could use array_map.

    $chars = array_map(function($item) {
        // at this point, you don't need an object, as json_encode do the
        // same for objects and associative arrays
        return [
            "id" =>$item->id,
            "name" => $item->name
        ];
    }, $chars);