使用PHP,我必须对以下列方式初始化的JSON编码流进行操作:
set = new Array();
set[n] = {"index": new Array()};
set[n].index[i] = {"x": xLoc, "y": yLoc, "id": "id#"};
最终导出到JSON编码的流,其结构如下所示:
[{"index":[{"x":156,"y":219,"id":"#1"},{"x":183,"y":229,"id":"#2"},{"x":540,"y":131,"id":"#3"},{"x":129,"y":300,"id":"#4"}]},{"index":[{"x":175,"y":214,"id":"#1"},{"x":188,"y":206,"id":"#2"},{"x":498,"y":231,"id":"#3"},{"x":150,"y":104,"id":"#4"}]},{"index":[{"x":123,"y":327,"id":"#1"},{"x":96,"y":256,"id":"#2"},{"x":12,"y":125,"id":"#3"},{"x":27,"y":32,"id":"#4"}]},{"index":[{"x":300,"y":145,"id":"#1"},{"x":104,"y":29,"id":"#2"},{"x":54,"y":11,"id":"#3"},{"x":29,"y":16,"id":"#4"}]},{"index":[{"x":11,"y":23,"id":"#1"},{"x":214,"y":16,"id":"#2"},{"x":423,"y":211,"id":"#3"},{"x":161,"y":89,"id":"#4"}]},{"index":[{"x":6,"y":202,"id":"#1"},{"x":432,"y":62,"id":"#2"},{"x":328,"y":55,"id":"#3"},{"x":93,"y":416,"id":"#4"}]}]
我的查询类似于:
sort.php?set=2&x=12&y=214
从上面的例子中,我想以递增的顺序为set [n]的每个索引返回/回显逗号分隔的 id#的 列表与查询的x和y位置相比,从最近到最远。
我是PHP的新手并且不知道从哪里开始。我希望我的问题有道理。提前谢谢!
答案 0 :(得分:2)
假设您在$set
(作为关联数组)
$sets = json_decode($json_data, true);
然后,您只需遍历数组的元素:
if(isset($sets[$_GET['set']])) {
$set = $sets[$_GET['set']];
$result = array();
foreach($set['index'] as $entry) {
$result[] = $entry['id']];
}
echo join(',', $result);
// or echo json_encode($result);
}
修改:忘记排序。您可以按点“Euclidean distance:
排序function d($x, $y) {
return sqrt(pow($_GET['x'] - $x, 2) + pow($_GET['y'] - $y, 2));
}
function sort_($a, $b) {
return d($a['x'], $a['y']) - d($b['x'], $b['y']);
}
$set = $sets[$_GET['set']]['index'];
usort($set, 'sort_');
$result = array();
foreach($set as $entry) {
$result[] = $entry['id'];
}
echo join(',', $result);
// or echo json_encode($result);