0

I have the two more php variable array how i convert this into json

 $tmp[0] $tmp[1] $tmp[2] $tmp[3] 

i have tried

$json_array=array( "dir"=>$tmp[0], "sym"=>$tmp[1], "bid"=>$tmp[2], "ask"=>$tmp[3] ); echo json_encode($json_array); 

it shows

{"dir":"down","sym":"oo","b":"1.35460","a":"1.35465"} {"dir":"down","sym":"pp","b":"1.64263","a":"1.64273"} {"dir":"down","sym":"qq","b":"104.498","a":"104.502"} {"dir":"up","sym":"rr","b":"0.88183","a":"0.88188"} {"dir":"down","sym":"ss","b":"1.09551","a":"1.09558"} 

but i need to change like this

[{"dir":"down","sym":"oo","b":"1.35460","a":"1.35465"},{"dir":"down","sym":"pp","b":"1.64263","a":"1.64273"},{"dir":"down","sym":"qq","b":"104.498","a":"104.502"},{"dir":"up","sym":"rr","b":"0.88183","a":"0.88188"},{"dir":"down","sym":"ss","b":"1.09551","a":"1.09558"}] 
0

6 Answers 6

2

Just do json Encode using Php function json_encode()

$json=json_encode($json_array); 
Sign up to request clarification or add additional context in comments.

Comments

1

Just create the data structure you want with php arrays and then json_encode($data);

If you want an additional array wrapper: (I'm using the more modern array syntax)

$data = [[ //or array(array( "dir"=>$tmp[0], "sym"=>$tmp[1], "bid"=>$tmp[2], "ask"=>$tmp[3] ]]; // or )) $data = json_encode($data); 

1 Comment

Also don't forget to first set your content type header: header('Content-type: application/json');
0

You need to json_enoce of your array:

$json_array=array( "dir"=>$tmp[0], "sym"=>$tmp[1], "bid"=>$tmp[2], "ask"=>$tmp[3] ); print_r(json_encode($json_array)); 

It will print the JSON representation of $json_array

documentation: https://www.php.net/json_encode

Comments

0
$json_array=array(); json_object1=array( "dir"=>$tmp[0], "sym"=>$tmp[1], "bid"=>$tmp[2], "ask"=>$tmp[3] ); $json_array[]=json_object1; $json_object2=array( "dir"=>$tmp[0], "sym"=>$tmp[1], "bid"=>$tmp[2], "ask"=>$tmp[3] ); $json_array[]=json_object2; json_encode($json_array); 

Comments

0

Use Json Encode to convert it to a PHP.

$data = array( "dir"=>$tmp[0], "sym"=>$tmp[1], "bid"=>$tmp[2], "ask"=>$tmp[3] ); echo json_encode($data); 

1 Comment

Definitely not what the OP is asking
0

Try this .

$json_array=array( "dir"=>$tmp[0], "sym"=>$tmp[1], "bid"=>$tmp[2], "ask"=>$tmp[3] ); echo json_encode(array($json_array)); 

Output :

[{"dir":null,"sym":null,"bid":null,"ask":null}] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.