我正在使用JSON方括号,并希望将其解码为两个多维数组。
这是JSON:
"results" : [[ /* WINNER BRACKET */
[[3,5], [2,4], [6,3], [2,3], [1,5], [5,3], [7,2], [1,2]],
[[1,2], [3,4], [5,6], [7,8]],
[[9,1], [8,2]],
[[1,3]]
], [ /* LOSER BRACKET */
[[5,1], [1,2], [3,2], [6,9]],
[[8,2], [1,2], [6,2], [1,3]],
[[1,2], [3,1]],
[[3,0], [1,9]],
[[3,2]],
[[4,2]]
], [ /* FINALS */
[[3,8], [1,2]],
[[2,1]]
]]
我希望将上面的内容解码为这种类型的PHP数组,如下所示:
$winner_results = array
(
array("match1",3,5),
array("match2",2,4),
array("match3",6,3),
array("match4",2,3),
array("match5",1,5),
array("match6",5,3),
array("match7",7,2),
array("match8",1,2),
array("match9",1,12),
array("match10",3,4),
array("match11",5,6),
array("match12",7,8),
array("match13",9,1),
array("match14",8,2),
array("match15",1,3)
);
$loser_results = array
(
array("match16",5,1),
array("match17",1,2),
array("match18",3,2),
array("match19",6,9),
array("match20",8,2),
array("match21",1,2),
array("match22",6,2),
array("match23",1,3),
array("match24",1,2),
array("match25",3,1),
array("match26",3,0),
array("match27",1,9),
array("match28",3,2),
array("match29",4,2)
);
$finals_results = array
(
array("match30",3,8),
array("match31",1,2),
array("match32",2,1)
);
是否可以将上述PHP数组编码为完全相同的JSON格式?
非常感谢您的帮助!
答案 0 :(得分:1)
这是一个解决方案。
注意:我使用动态变量名($$ varname)为每个组创建自己的数组(获胜者,松散者,最终)。
<?php
$results = '[[
[[3,5], [2,4], [6,3], [2,3], [1,5], [5,3], [7,2], [1,2]],
[[1,2], [3,4], [5,6], [7,8]],
[[9,1], [8,2]],
[[1,3]]
], [
[[5,1], [1,2], [3,2], [6,9]],
[[8,2], [1,2], [6,2], [1,3]],
[[1,2], [3,1]],
[[3,0], [1,9]],
[[3,2]],
[[4,2]]
], [
[[3,8], [1,2]],
[[2,1]]
]]';
// These are the group names
$names = array('winner_results','looser_results','final_results');
// First we make a PHP array out of the JSON (object) string
$resarr = json_decode($results);
// Then we create a new array for each group, re-organizing the input array $resarr
$cnt = 0; // The counter we use for qualifying the 'match' identifiers
foreach($resarr as $groupix => $group) {
$arrname = $names[$groupix];
$$arrname = array(); // Create an empty array for the group
foreach($group as $items) {
foreach($items as $item) {
// Add data (array) to the group array
$cnt++;
array_push($$arrname,array('match'.$cnt,$item[0],$item[1]));
}
}
}
// And finally we display the created arrays
foreach ($names as $arr) {
echo '<h3>'.$arr.'</h3><pre>'; print_r($$arr); echo '</pre>';
}
?>
答案 1 :(得分:0)
这是一个array_merge' of the 'sub-arrays' of each of the
赢家,输家,最终阵列。
$allResults = json_decode($json, true);
$results = current($allResults); // get the three sub-arrays
$winner = call_user_func_array('array_merge', $results[0]);
$loser = call_user_func_array('array_merge', $results[1]);
$finals = call_user_func_array('array_merge', $results[2]);
$json = '{"results": [[
[[3,5], [2,4], [6,3], [2,3], [1,5], [5,3], [7,2], [1,2]],
[[1,2], [3,4], [5,6], [7,8]],
[[9,1], [8,2]],
[[1,3]]
], [
[[5,1], [1,2], [3,2], [6,9]],
[[8,2], [1,2], [6,2], [1,3]],
[[1,2], [3,1]],
[[3,0], [1,9]],
[[3,2]],
[[4,2]]
], [
[[3,8], [1,2]],
[[2,1]]
]]}';