PHP Array for JS Array

Asked

Viewed 106 times

3

I have the following array in PHP

Array
(
    [0] => Array
    (
        [Funcionarios] => Array
            (
                [id] => 3
                [nome] => Funcionario Teste
                [assistmed] => 10
                [assistodont] => 1
            )

    )

    [1] => Array
    (
        [Funcionarios] => Array
            (
                [id] => 1
                [nome] => Paulo Teste 2
                [assistmed] => 2
                [assistodont] => 2
            )

    )

I need to turn him into JS.

I tried to

js_arr = JSON.parse('<?php echo JSON_encode($funcionarios2);?>');

And I would like to handle it with js. However I can’t get the data, I tried the following commands:

alert(js_arr.id[0]);
alert(js_arr[id][0]);

What’s the right way?

1 answer

2


In that case the best thing to do is to use a console.log only in the variable to find out how the structure is coming, so:

console.log(js_arr);

After it returns the structure, watch carefully to find out how to call it, you can use the jsonformatter for easy reading.

[  
   {  
      "Funcionarios":{  
         "id":"3",
         "nome":"Funcionario Teste",
         "assistmed":"10",
         "assistodont":"1"
      }
   },
   {  
      "Funcionarios":‌​{  
         "id":"1",
         "nome":"Pa‌​ulo Teste 2",
         "assistmed":"2",
         "assistodont":"2"
      }
   },
   {  
      "Funcionarios":{  
         "id":"5",
         "nome":"Sem Med/Odont",
         "assistmed":"0",
         "assistodont":"0"
      }
   }
]

Dai now becomes easy to figure out how to get to the field you want:

var nomeFuncionario1 = js_arr[0]['Funcionarios'].nome
  • 1

    Perfect. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.