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 Link to comment https://forums.phpfreaks.com/topic/280588-how-to-use-jason_encode/ Share on other sites More sharing options...
0xMatt Posted July 28, 2013 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"]} 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: "[email protected]" which actually gives $data['name'] = "abc" $data['email'] = "[email protected]" {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", "[email protected]") i actually dont want to get 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 Have you tried just setting your array like this: $data = array(); $data[] = "abc"; $data[] = "[email protected]"; or pretty much exactly as you just wrote it: $data = array("abc", "[email protected]"); 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 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
Archived
This topic is now archived and is closed to further replies.