laraib
laraib

Reputation: 631

Converting my php array to equivalent jQuery Array

I have an array in PHP and want to use that data inside my Jquery, I have converted that to json and here is my full code.

$mine = array(
'new' => 'new',
'old' => 'old'
);

and I have converted it like this

$result = json_encode(array_values($cat));

and now I got my results like show below:

[{"new":"new","old":"old"}]

this is wrong one, because I want it to be like this way.

[
{"new":"new"},
{"old":"old"}
]

I don't know where am I doing any thing wrong but I am unable to get this simple thing done ... any one to help me out of this simple question please ... I really have been through many earlier questions like json_encode sparse PHP array as JSON array, not JSON object

But still unable to get this work for me, any one there to help me out pelase ???

Upvotes: 0

Views: 84

Answers (3)

GhanuBha
GhanuBha

Reputation: 1

You can also do like this:

var encodedVar=json_encode($array_nm);
var js_array=$.paseJSON(encodedvar);
for(var i=0;i<js_array.length;i++){
    console.log(js_array[i]);//it will display value by index just like php array....
}

Upvotes: 0

Iarwa1n
Iarwa1n

Reputation: 460

Your array has to look like this in PHP:

$mine = array(
array('new' => 'new'),
array('old' => 'old')
);

json_encode transforms a php array to a json object ( {} )if it is a dictionary (Associative) and transforms it to a json array ( [] ) if it is a list without keys.

Upvotes: 1

teo van kot
teo van kot

Reputation: 12491

You got a bit wrong structure of your php object it should be:

$mine = array(
   array('new' => 'new'),
   array('old' => 'old')
);

Check example.

Upvotes: 0

Related Questions