[英]if not in array -> array.push
我正在尝试使用JSON提要中的唯一元素在javascript中创建一个数组。 也许我想在PHP中有很多,但有一个简单的脚本如下工作。
$this = array();
foreach($array as $key => $value) {
if (!in_array($value,$this)) {
array_push($this,$value);
}
}
在JS中它没有:
var this = new Array();
$.each(data, function(i,field) {
var value = field['needed'];
if (!$.inArray(value, this)) {
this.push(value);
}
}
它只是this
添加了每个field['needed']
。
完整代码,以便您了解我如何获得我的JSON
$(function() {
$("#wtf").empty();
$.getJSON("http://localhost/ahsmedia/openingsuren/api.php?first=" + cal.currentDate.format('d-m-Y'),
function(data) {
var camp = new Array();
$.each(data, function(i,field) {
var dt = field['datum'];
var ca = field['campus'];
var ca = ca.toLowerCase();
if ($.inArray(ca, camp)) {
camp.push(ca);
}
$("#wtf").append(field['campus'] + ' ' + cal.currentDate.format('d-m-Y') + ': ' + " " + field['open'] + "-" + field['close'] + " " + field['type'] + "<br />");
});
console.log(camp);
});
});
JSON看起来像:
[
{
"datum": "2015-01-07",
"type": "normal",
"campus": "Kantienberg",
"open": "08:00:00",
"close": "18:00:00"
},
{
"datum": "2015-01-07",
"type": "normal",
"campus": "Kattenberg",
"open": "08:00:00",
"close": "18:00:00"
},
{
"datum": "2015-01-07",
"type": "normal",
"campus": "Mariakerke",
"open": "08:30:00",
"close": "18:00:00"
},
{
"datum": "2015-01-07",
"type": "normal",
"campus": "Sint-Amandsberg",
"open": "09:30:00",
"close": "11:30:00"
},
{
"datum": "2015-01-07",
"type": "normal",
"campus": "Sint-Amandsberg",
"open": "12:00:00",
"close": "17:30:00"
},
{
"datum": "2015-01-07",
"type": "normal",
"campus": "Sint-Annaplein",
"open": "08:15:00",
"close": "12:30:00"
},
{
"datum": "2015-01-07",
"type": "normal",
"campus": "Sint-Annaplein",
"open": "13:30:00",
"close": "17:30:00"
}
]
在检查字段是否在数组中之前,我可能忘记了一个重要的步骤,但我对此很新,所以我找不到它。
要清楚,我需要一个与每个独特校园相似的阵列
['Kantienberg','Kattenberg','Mariakerke','Sint-Amandsberg','Sint-Annaplein']
但我明白了
["kantienberg", "kattenberg", "mariakerke", "sint-amandsberg", "sint-amandsberg", "sint-annaplein", "sint-annaplein"]
如果数组中不存在值, $.inArray()
将返回-1
。 当用作布尔值时, -1
等于true
。 您需要更改条件以显式检查-1
:
if ($.inArray(ca, camp) == -1) {
camp.push(ca);
}
我的解决方案如下:
var camp = {};
$.each(data, function(i, field) {
var dt = field['datum'];
var openClose = field['open'] + "-" + field['close'];
var ca = field['campus'];
if (camp[ca]) {
camp[ca].push(openClose);
} else {
camp[ca] = [openClose];
}
});
这会产生一个对象,它将校园名称映射到开放时间,如下所示:
"name" -> ["open-close", "open-close", ...]
创建对象后,我们只需将其附加到DOM:
for (prop in camp) {
$("#wtf").append(prop + " ");
for (var i = 0; i < camp[prop].length; i++) {
$('#wtf').append(camp[prop][i]);
if (i !== camp[prop].length - 1) {
$('#wtf').append(" ");
}
}
$('#wtf').append('<br>');
}
我之所以认为这种方法更适合您,是因为这样可以节省所有开启和关闭时间。 在另一种方法中,只剩下其中一个间隔。
小提琴就在这里 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.