PHP多维数组到JavaScript
我想在Javascript函数中打印PHP数组的数据。。。问题是,它不起作用。以下是数据在PHP中合成的方式:PHP多维数组到JavaScript,javascript,php,arrays,json,multidimensional-array,Javascript,Php,Arrays,Json,Multidimensional Array,我想在Javascript函数中打印PHP数组的数据。。。问题是,它不起作用。以下是数据在PHP中合成的方式: $daten = array(); $anzahl = array(); $leads = array(); if ($result = $this->databaseConnection->query($sql)) { while ($row = $result->fetch_assoc()) { $daten[] = $row["Datum
$daten = array();
$anzahl = array();
$leads = array();
if ($result = $this->databaseConnection->query($sql)) {
while ($row = $result->fetch_assoc()) {
$daten[] = $row["Datum"];
$anzahl[] = $row["Anzahl"];
}
$this->logger->lwrite('Leads: '. $leads);
$leads[] = array(array("daten" => $daten), array("anzahl" => $anzahl));
return json_encode($leads);
}
这就是JavaScript POST请求的内容:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
xhttp.open("POST", "/requestLeadClicksController.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(jQuery('#formToRequestLeadClicks').serialize());
这是我在console.log(This.responseText)上看到的内容代码>:
而this.responseText.daten
,this.responseText[0]
,this.responseText[0].daten
或this.responseText[daten]
正在仅打印数据数组。我想得到的只是:
"2017-12-21","2017-12-22","2017-12-23"
"1","2","1"
anzahl阵列也是如此。我也只想要这个:
"2017-12-21","2017-12-22","2017-12-23"
"1","2","1"
我将感谢任何帮助!
亲切的问候 您有一个数组,其中包含一个包含字符串数组的对象数组。要深入到字符串的最内层数组,需要两个数组索引,后跟一个对象属性
datenArray = responseText[0][0].daten,
anzahlArray = responseText[0][1].anzahl;
let responseText=[[{“daten”:[“2017-12-21”、“2017-12-22”、“2017-12-23”],{“anzahl”:[“1”、“2”、“1”]}],
datenArray=responseText[0][0]。日期,
Anzahlaray=responseText[0][1]。anzahl;
console.log(datenArray);
控制台日志(anzahlArray)代码>如果希望自动返回,可以使用递归迭代器(我使用jQuery来实现)。此迭代器仅在要返回的键是关联键(不是数字键)的情况下才起作用,尽管它可以更改为执行您想要的任何操作:
var arr = [[{"daten":["2017-12-21","2017-12-22","2017-12-23"]},{"anzahl":["1","2","1"]}]];
var arrfin = {};
function recurse(array)
{
$.each(array,function(k,v){
if(typeof v === "object") {
if(typeof k !== "number")
arrfin[k] = v;
else
recurse(v);
}
});
}
recurse(arr);
console.log(arrfin.daten);
console.log(arrfin.anzahl);
这将在控制台中提供:
["2017-12-21", "2017-12-22", "2017-12-23"]
["1", "2", "1"]
遗憾的是没有为我工作。。。我得到:Uncaught TypeError:无法读取XMLHttpRequest.xhttp.onreadystatechange((索引):1061)处未定义的属性“anzahl”
它应该是anzahlArray=responseText[0][0]。anzahl代码>而不是anzahlArray=responseText[0][1]代码>响应文本,字符串不是对象。你必须现在就开始工作,谢谢!:)