Jump to content

how to use jason_encode


new_member
Go to solution Solved by 0xMatt,

Recommended Posts

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
Share on other sites

  • Solution

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
Share on other sites

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

Link to comment
Share on other sites

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 by denno020
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.