new_member Posted July 28, 2013 Share Posted July 28, 2013 Hi, i have an array with five values. I want to encode the array using json_encode in format: {"value1":"val","data":["name", "email"]} where value 1 is a paremeter in php and data is an array. But if i use json_encode it gives me different output here is my code: $arr['value1'] = 'val';$arr['data'] = $data //arrayjson_encode($arr); it gives me {"value1":"val1","data":{"name", "email"}} can any one tell men how to encode the array in above format?? thanks Quote Link to comment https://forums.phpfreaks.com/topic/280588-how-to-use-jason_encode/ Share on other sites More sharing options...
Solution 0xMatt Posted July 28, 2013 Solution Share Posted July 28, 2013 The issue is with the array stored in your $data variable. This code: $array = array( 'value1' => 'val', 'data' => array('name','email') ); print_r(json_encode($array)); Outputs: {"value1":"val","data":["name","email"]} Quote Link to comment https://forums.phpfreaks.com/topic/280588-how-to-use-jason_encode/#findComment-1442485 Share on other sites More sharing options...
new_member Posted July 28, 2013 Author Share Posted July 28, 2013 Thanks for the reply. The solution you provided actually worked. But i found another problem with my array as i am passing the array values through ajax and getting using $_GET. I have two fields "name" and "email" and values are passed as name: "abc" email: "test@test.com" which actually gives $data['name'] = "abc" $data['email'] = "test@test.com" {data:{"name":"abc"}} etc is there any way to pass the array in format without name and email label and pass the values only like data = array("abc", "test@test.com") i actually dont want to get Quote Link to comment https://forums.phpfreaks.com/topic/280588-how-to-use-jason_encode/#findComment-1442492 Share on other sites More sharing options...
denno020 Posted July 28, 2013 Share Posted July 28, 2013 (edited) Have you tried just setting your array like this: $data = array(); $data[] = "abc"; $data[] = "test@test.com"; or pretty much exactly as you just wrote it: $data = array("abc", "test@test.com"); However personally I would use the key-value pairs, as that way you know exactly what data you're grabbing in the javascript, instead of just an index number. Denno Edited July 28, 2013 by denno020 Quote Link to comment https://forums.phpfreaks.com/topic/280588-how-to-use-jason_encode/#findComment-1442495 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.