Сканирование многомерного массива json_encoded

Извините за форматирование — в этом вопросе он постоянно выдавал мне ошибки «у вас есть неотформатированный код». У меня есть код, который состоит из холста, который печатает изображение. Затем я отслеживаю координаты мыши пользователя, и если они совпадают с координатами, найденными в текстовом файле, я хочу подсказать пользователю. Это веб-приложение, дополняющее программу C ++ OpenCV, которая обнаруживает капли и координаты, в которых они существуют. Текстовый файл в следующем формате: label x y,

001 101 305

это строка для координаты (101, 305) в BLOB-объекте 001. PHP читает каждую строку и просто взрывается в пробелах.

Текстовый файл выглядит так:

001 101 303
001 101 304
001 101 305
001 101 306
001 101 307
001 101 308
001 101 309
001 101 310
001 102 301
001 102 302
<script>  // functions to make canvas and place PNG overlay image

<?php
$XYFile = fopen("cpp/textdump/coordinates/imagetesting.txt.txt","r") or die ("file reading error");
$coordinates = array(); // create coordinates array

while (!feof($XYFile)) { // while not at last line of file
$uncatXY = fgets($XYFile); // read one line of file
$splitXY = explode(" ", $uncatXY); // create new array element when a space is present
$label = $splitXY[0]; // declare blob label
$x = $splitXY[1]; // declare x
$y = $splitXY[2]; // declare y
array_push($coordinates, $label, $x, $y);
} // push into coordinates array

fclose($XYFile); // close file
?>

var js_array = <?php echo(json_encode($coordinates)); ?>  // convert PHP array to javascript object notation format
// requires PHP 5.2 or higher, which I believe to be on the server.  It's certainly on my localhost server.
console.log(js_array); // dev


$(document).ready(function() {
window.onload = function() {
var c = document.getElementById("solarCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#00FFFF"; // cyan fill
var img = document.getElementById("testimage");
img.src = 'cpp/images/PNG/imagetesting.png';   //"cpp/images/" + date + ".png";
ctx.drawImage(img, 0, 0);

c.addEventListener('click', function() { }, false);

// functions for color & coordinates on mouse movement/clicl
$('#solarCanvas').mousemove(function(e) {
var c = document.getElementById("solarCanvas");
var ctx = c.getContext("2d"); // temp declaration bug fix -- can't find root cause, so redec
var pos = findPos(this);
var x = e.pageX - pos.x;
var y = e.pageY - pos.y;
var coord = "x=" + x + ", y=" +y;
var p = ctx.getImageData(x, y, 1, 1).data;
var hex = ("#" + 000000 + rgbToHex(p[0], p[1], p[2]).slice(-6));
$('#status').html(coord + "<br>" + hex);
console.log(x + "," + y + "---" + coord + " at " + hex);
});

$('#solarCanvas').click(function(e) {
var c = document.getElementById("solarCanvas");
var ctx = c.getContext("2d");
var pos = findPos(this);
var xNum = e.pageX - pos.x;
var yNum = e.pageY - pos.y;
var xStr = xNum.toString();
var yStr = yNum.toString();

for(var i = 0; i < js_array.length; i++) {
if(js_array[i] === xStr) {
return i;
console.log(i);
if(i > -1) {
alert("yahoo!");
}
}
}

console.log(js_array);
console.log(xStr);
console.log(yStr);
});
}
});

// old architecutre
// mixed array_search ( mixed $needle, array $haystack [, bool $strict = false ] );
// searches haystack for needle
// pseudocode
//if ((e.pageX - pos.x) exists in col 2 && (e.pageY-pos.y) is in same row in col 3) {

</script>

Я прошел через много версий этого кода и выкладываю то, что имею сейчас. Я работаю строго с координатой X в данный момент. Как только это сработает, я добавлю в Y.
[…] Я учел тот факт, что PHP взорвется & json_encode сохраняет строки, поэтому я сделал функцию .toString (), но это, похоже, не помогло вообще. Например, мой консольный журнал будет что-то вроде x / y / pos of x в массиве / pos of y в массиве

101
305
-1
-1

1

Решение

Вот небольшое переписывание вашего кода.

Что я сделал:

  1. Изменен синтаксический анализ CSV для разделения на строки по 3 столбца, для простоты используется модель итератора.
  2. Изменен ваш JS, чтобы он соответствовал x-координатам в строке [1] и y-координатам в строке [2]
  3. Не уверен, что другой код предназначен для успеха … похоже, вы все еще работаете над этим.

Код PHP:

<?php
$file = file("cpp/textdump/coordinates/imagetesting.txt.txt"");
$coordinates = array();
for ($line in $file) {
array_push($coordinates, explode(" ", $line);
}
?>
var coords = <?= json_encode($coordinates) ?>;

JS:

$('#solarCanvas').click(function(e) {
var c = document.getElementById("solarCanvas");
var ctx = c.getContext("2d");
var pos = findPos(this);
var xNum = e.pageX - pos.x;
var yNum = e.pageY - pos.y;
var xStr = xNum.toString();
var yStr = yNum.toString();

for(var i = 0; i < coords.length; i++) {
if(coords[i][1] === xStr && coords[i][2] === yStr) {
return i;
console.log('coord found', coords[i]);
}
}
console.log(coords);
console.log(xStr);
console.log(yStr);
});
0

Другие решения

Других решений пока нет …