icant想出如何从我的数组中编码一个有效的json 尝试了每一种可能的方式来编码json我没有运气 谢谢你的时间
<?php
// this array is very large i used small piece as example
$listarray = array(
array(87,108,173,0,0),
array(87,108,173,0,1),
array(87,108,173,0,2),
array(87,108,173,0,3),
array(87,108,173,0,4),
array(87,108,173,0,5),
array(79,99,163,0,6),
array(79,99,163,0,7),
array(79,99,163,0,8),
array(79,99,163,0,9),
array(92,97,158,0,10),
array(92,97,158,0,11),
array(76,91,153,0,12),
array(79,99,163,0,13),
array(76,91,153,0,14),
array(92,97,158,0,15),
array(76,91,153,0,16),
array(76,91,153,0,17),
array(133,157,215,1,47),
array(133,157,215,1,48),
array(133,157,215,1,49),
array(133,157,215,1,50),
array(133,157,215,1,51),
array(133,157,215,1,52),
array(133,157,215,1,53),
array(143,168,222,1,54),
array(156,180,227,1,55),
array(156,180,227,1,56),
array(142,175,243,1,57),
array(156,180,227,1,58),
array(156,180,227,1,59),
array(156,180,227,1,60),
array(133,157,215,1,61));
for ($key = 0, $size = count($listarray); $key < $size; $key++) {
$array = array_values($listarray[$key]);
$line = $array[3]+1; //+1 start counting from 1
$loc = $array[4]+1; //+1 start counting from 1
$Name = $array[0].'_'.$array[1].'_'.$array[2];
$data = new StdClass();
$data->$line->$Name = array("$loc",);
$json = json_encode($data,JSON_PRETTY_PRINT);
echo $json."<br>";
//// echo give somthing like this and it is unusable for me
//{ "1": { "87_108_173": [ "1" ] } }
//{ "1": { "87_108_173": [ "2" ] } }
//{ "1": { "87_108_173": [ "3" ] } }
//{ "1": { "87_108_173": [ "4" ] } }
//{ "1": { "87_108_173": [ "5" ] } }
//{ "1": { "87_108_173": [ "6" ] } }
////
$fh = fopen("jsonout.json", 'w')or die("Error opening output file");
fwrite($fh, json_encode($data,JSON_PRETTY_PRINT));
fclose($fh);
}// end of for loop
?>
//和jsonout.json的内容无效
//需要的输出就像这样
// json blew是用app制作并经过验证的
{
"1": {
"87_108_173": [
"1",
"2",
"3",
"4",
"5",
"6"
],
"92_97_158": [
"11",
"12",
"16"
],
"79_99_163": [
"7",
"8",
"9",
"14"
],
"76_91_153": [
"13",
"15",
"17",
"18"
]
},
"2": {
"156_180_227": [
"56",
"57",
"59",
"60",
"61"
],
"142_175_243": [
"58"
],
"133_157_215": [
"48",
"49",
"50",
"51",
"52",
"53",
"54",
"62"
],
"143_168_222": [
"55"
]
}
}
答案 0 :(得分:1)
$listarray = array(
array(87,108,173,0,0),
array(87,108,173,0,1),
array(87,108,173,0,2),
array(87,108,173,0,3),
array(133,157,215,1,47),
array(133,157,215,1,48),
array(133,157,215,1,49),
array(133,157,215,1,50),
array(133,157,215,1,51),
array(133,157,215,1,52),
);
$resultArray = array();
foreach ($listarray as $row) {
$ind = $row[3] + 1;
$name = $row[0] . '_' . $row[1] . '_' . $row[2];
$val = $row[4] + 1;
if (!isset($resultArray[$ind])) {
$resultArray[$ind] = array();
}
if (!isset($resultArray[$ind][$name])) {
$resultArray[$ind][$name] = array();
}
$resultArray[$ind][$name][] = $val;
}
echo json_encode($resultArray, JSON_PRETTY_PRINT);
欢迎你;)