I am trying to get the input from a 2d php string array and convert the values in arr[i][1] (where i can be treated as a row and 1 as column in matrix) to integer as follows:
JavaScript function:
var _input = <? php echo json_encode($output); ?> ; //2D String
var _sro = []; //string
var _src = []; //string
var _sru = []; //string
var aL = _input.length;
for (var i = 0; i < aL; i++) {
_sro.push(_input[i][0]); //string
_src.push(_input[i][1]); //string
_sru.push(_input[i][2]); //string
}
alert(_src.toString()); //result = 1,1,2,9,6,1,24...
alert(typeof(_src).toString()); //res = string
var _lb = new Array(); //empty
var _dt = new Array(); //empty
for (var i = 0; i < aL; i++) {
_dt.push(parseInt(_src[i])); //convert to int and push to arr
}
alert(_dt.toString()); //result = NaN,NaN,NaN,NaN.....
alert(typeof(_dt).toString()); //res = string
_lb = _sro;
The problem I am experiencing is that the end output for each value of _dt is NaN which means that it does not get converted appropriately. To resolve this I have tried following:
- using parseInt
- using Number()
- using the "+" operator
- using both parseInt and Number()
For example:
for (var i = 0; i < aL; i++) {
_dt.push(Number(parseInt(_src[i]))); //convert to int and push to arr
}
and all these have failed. I am really lost and I have ran out of ideas after 2 days of googling and maybe someone in their wisdom will be able to help for which thank you in advance.
EDIT:
PHP Function:
the below function generates the PHP array passed through to JS:
//set error reporting
error_reporting(E_ALL & ~E_NOTICE);
//set variables
$result = array();
$output = array();
//read in csv file
foreach(file("1OnScreen.csv") as $key => $str) {
if ($key == 0)
continue; // skip first line
$values = str_getcsv($str, "\t", '', '');
$result[] = $values;
}
$output = $result;
CSV DATA
The CSV File contains following data and the delimiter is \t:
Owner Count Unassigned Other
AA1 1 0 1
AD 1 0 1
AR 2 0 2
BW 9 0 9
CM 6 0 6
CT 1 0 1
DB 24 0 24
EU 8 0 8
GM 5 0 5
GO 21 0 21
JF 1 0 1
JW 2 0 2
NH 10 0 10
RB 2 0 2
SPC 4 0 4
SP 2 0 2
TC 2 0 2
TG 1 0 1
VS 4 0 4
JSON Output in JS
Output of _input
as I see it when running alert(_input)
i think that the comma on the beginning of the new lines can be impacting the conversion and making it fail but I do not know how to go around that.
AA1,1,0,1
,AD,1,0,1
,AR,2,0,2
,BW,9,0,9
,CM,6,0,6
,CT,1,0,1
,DB,24,0,24
,EU,8,0,8
,GM,5,0,5
,GO,21,0,21
,JF,1,0,1
,JW,2,0,2
,NH,10,0,10
,RB,2,0,2
,SPC,4,0,4
,SP,2,0,2
,TC,2,0,2
,TG,1,0,1
,VS,4,0,4