0

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 ???

Community
  • 1
  • 1
laraib
  • 611
  • 5
  • 16
  • 1
    Try to use `$result=json_encode($mine)` in php and `$.parseJSON(json)` in jQuery. – Miron Dec 13 '16 at 13:47
  • In the comments to an answer you showed your "actual code". Please put it in the question too, since it seems to be pretty different. – Aioros Dec 13 '16 at 15:42

3 Answers3

1

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.

Iarwa1n
  • 460
  • 3
  • 12
  • here is my actual code $cat = array(); $categories = $categories = get_categories(array('hide_empty' => true)); //print_r($categories); foreach($categories as $category){ $cat['name'][$category->name] = $category->slug; } – laraib Dec 13 '16 at 13:57
  • Array ( [0] => Array ( [another] => another ) [1] => Array ( [Uncategorized] => uncategorized ) ) now this is my array in php ... how can i make it like I already shown structure in jquery ? – laraib Dec 13 '16 at 14:01
  • This looks already right as your key/value pairs are inside extra array. Does json_encode not work correclty with this? – Iarwa1n Dec 13 '16 at 14:51
0

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

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

Check example.

teo van kot
  • 12,350
  • 10
  • 38
  • 70
  • Array ( [0] => Array ( [another] => another ) [1] => Array ( [Uncategorized] => uncategorized ) ) now this is my array in php ... how can i make it like I already shown structure in jquery ? – laraib Dec 13 '16 at 14:02
  • the problem is that I am getting that data from ajax success method and then pushing that respone json to my jquery array ... then I want to use that array ... any one who can guide me properly plz ? – laraib Dec 13 '16 at 14:04
0

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....
}
GhanuBha
  • 142
  • 7