1

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?

Krupesh Kotecha
  • 2,396
  • 3
  • 21
  • 40
Inception
  • 455
  • 1
  • 9
  • 32
  • Not possible, JavaScript doesn't support associative arrays. The goal object in the example is possible, though. – Teemu Jun 15 '18 at 06:58
  • Try this `json_encode($chars, true)` – Jacek B Budzynski Jun 15 '18 at 06:58
  • @Teemu : I have a question, is the target format I want even an associative array. It is for the easyautocomplete plugin. Is it a JSON representation? – Inception Jun 15 '18 at 07:00
  • No, it is not an associative array, at least not in the same meaning what the term means in PHP. It is a JavaScript object, and it is specifically not a "JSON object". You can very well do what Jacek said, it is a trivial task to convert a JSON string to JavaScript object at the client-side. – Teemu Jun 15 '18 at 07:03
  • Jacek's suggestion made no difference for some reason. I still need to figure out how to convert my data to that format for the easyautocomplete plugin :( – Inception Jun 15 '18 at 07:08
  • @Teemu `js_data` is an array of objects, each containing an id and name property. `0: Object { id: "10", name: "Cyclops", … } ​​ 1: Object { id: "11", name: "Professor X", … }` I want all of that to go into the 'data' property of `character` variable like I've put in my original post. – Inception Jun 15 '18 at 07:19
  • But won't just `var characters = {data: JSON.parse(JSON.stringify(js_data))};` do what you need? Or even simpler: `var characters = {data: js_data};`, if the original data object is not needed later. – Teemu Jun 15 '18 at 07:28
  • But it seems when I do that, it seems each value inside data is an object containing name and id instead of just name and id. https://i.imgur.com/WcmV2ll.png – Inception Jun 15 '18 at 07:32
  • ?? That's what is has to be, like I said, there's no associative arrays in JS. That's also what you say you need: `characters = {data: [{"name": "Cyclops", id: 10}, ... ]}`. – Teemu Jun 15 '18 at 07:45
  • @Teemu But the problem is, the plugin then gives objects as suggestions: https://i.imgur.com/wMT1PBj.png – Inception Jun 15 '18 at 07:51
  • Then you've to check what you really need. Whaat the plugin should suggest? The names or ids or both? – Teemu Jun 15 '18 at 07:52
  • From the manual for the plugin: https://i.imgur.com/EW2m09Z.png – Inception Jun 15 '18 at 07:55
  • Okay, it's just that you asked to convert into a form which actually is not needed. Those who have already posted answers, can surely answer this question too. Please ping both answerers for changes of the question. – Teemu Jun 15 '18 at 07:57
  • Thank you. It seems I was asking for the wrong solution the entire time. I'm extremely sorry for that. – Inception Jun 15 '18 at 07:59
  • Don't worry, you were not the first to ask something they actually don't need = ). – Teemu Jun 15 '18 at 08:02

2 Answers2

1

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);
Philipp
  • 15,377
  • 4
  • 35
  • 52
  • It seems nothing is entering the characters variable when I do this. console.log returns nothing for `characters` variable. – Inception Jun 15 '18 at 07:44
  • Is this what you want? https://pastebin.com/yPS8TnuZ I have added the relevant html/js/php portion and in the bottom, the console.log and var_dump outputs. – Inception Jun 15 '18 at 08:34
  • In the above paste, ignore the slight id name mismatch, I have fixed it already. – Inception Jun 15 '18 at 08:35
1

You can convert the last javascript JSON array to

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

}

By using your PHP code result

0: {…}

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

Use need to store the final below result to a js variable and you can use forEach to push the variable to another js array for example if the result is

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

then use

var b=[]
a.forEach(x=>{b.push(x.data)});

it Will get the below result

(2) [{…}, {…}] 0 : {id: "10", name: "Cyclops"} 1 : {id: "11", name: "Professor X"} length : 2 proto : Array(0)

I hope it will help you

Anuragh KP
  • 748
  • 11
  • 21