我还有两个php变量数组如何将其转换为json
$tmp[0]
$tmp[1]
$tmp[2]
$tmp[3]
我试过了
$json_array=array(
"dir"=>$tmp[0],
"sym"=>$tmp[1],
"bid"=>$tmp[2],
"ask"=>$tmp[3]
);
echo json_encode($json_array);
显示
{"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"}
但我需要像这样改变
[{"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 :(得分:2)
使用Php函数json_encode()
进行json编码$json=json_encode($json_array);
答案 1 :(得分:1)
只需使用php数组创建所需的数据结构,然后json_encode($data);
如果你想要一个额外的数组包装器:(我正在使用更现代的数组语法)
$data = [[ //or array(array(
"dir"=>$tmp[0],
"sym"=>$tmp[1],
"bid"=>$tmp[2],
"ask"=>$tmp[3]
]]; // or ))
$data = json_encode($data);
答案 2 :(得分:0)
你需要你的数组的json_enoce:
$json_array=array(
"dir"=>$tmp[0],
"sym"=>$tmp[1],
"bid"=>$tmp[2],
"ask"=>$tmp[3]
);
print_r(json_encode($json_array));
它将打印$json_array
答案 3 :(得分:0)
使用 Json Encode 将其转换为PHP。
$data = array(
"dir"=>$tmp[0],
"sym"=>$tmp[1],
"bid"=>$tmp[2],
"ask"=>$tmp[3]
);
echo json_encode($data);
答案 4 :(得分: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);
答案 5 :(得分:0)
试试这个。
$json_array=array(
"dir"=>$tmp[0],
"sym"=>$tmp[1],
"bid"=>$tmp[2],
"ask"=>$tmp[3]
);
echo json_encode(array($json_array));
输出:
[{"dir":null,"sym":null,"bid":null,"ask":null}]