确定数组中有多少连续字段为空

时间:2017-05-16 13:14:48

标签: php arrays

我有一个包含变量的数组:
$shippingtimearr = array("", "1630", "1530", "1530", "1530", "", "");

这个数组中的每个字段代表一个工作日。
我需要确定有多少连续字段为空,具体取决于当天(“起始字段”)。

例如:
如果开头为$shippingtimearr[5],则应该返回3,因为下一个“星期一”($shippingtimearr[0])为NULL
如果开始是一个不是NULL的数组值,它应该返回0;

我尝试像这样创建一个“for”循环:

for( $i = 2; $shippingtimearr[$i] = 0; $i++ ) {
            $counter++;
         }

但它没有用,显然,这并不能解释为什么应该再次循环“周”以确定下周的第一天是否为“NULL”。

4 个答案:

答案 0 :(得分:0)

$shippingtimearr = array("", "1630", "1530", "1530", "1530", "", "");
$contains_empty = count($shippingtimearr) - count(array_filter($shippingtimearr));

答案 1 :(得分:0)

可能你正在寻找一些更简单的答案,比如

const fs = require('fs');
const mqtt = require('mqtt');

// Parts of URL and Path
const hcp_account_id = 'WWWWWWWWW';
const hcp_landscape_host = '.hana.ondemand.com' // this is used on PROD with Client Certificate Authentication
const my_endpoint_url_path = '/com.sap.iotservices.mms/v1/api/ws/mqtt';

//Certificate
const client_p12 = "./YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY.p12";

// the following values need to be taken from the IoT Cockpit
const device_id = 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX';
const message_type_id_From_device = 'ZZZZZZZZZZZZZZZZZZZZ';

// for down- upstream communication
var my_publish_topic = "iot/data/" + device_id;
var my_subscription_topic = "iot/push/" + device_id;

var my_endpoint = "iotmms" + hcp_account_id + hcp_landscape_host;

var wsoptions =
    {
        host: my_endpoint,
        port: 443,
        pfx: fs.readFileSync(client_p12),
        passphrase: 'AAAAA',
        checkServerIdentity: false,
        protocol: 'mqttv3.1',
        protocolVersion: 13,
        perMessageDeflate: true,
        client_max_window_bits: true
    }

var options =
    {
        wsOptions: wsoptions,
        clientId: device_id,
        protocolId: 'MQIsdp',
        protocolVersion: 3,
        protocol: 'wss',
        hostname: my_endpoint,
        port: 443,
        path: my_endpoint_url_path
    }

const mqttc = mqtt.connect(options);

mqttc.subscribe(my_subscription_topic, 0);

mqttc.on('connect', () => console.log('connected!'));

mqttc.on('error', (msg) => console.log('error: ' + msg));

mqttc.on('offline', (msg) => console.log('offline: ' + msg));

mqttc.on('close', (msg) => console.log('close: ' + msg));

// message is Buffer
mqttc.on('message', (topic, message) => console.log('message(' + topic + '): ' + message.toString()));

答案 2 :(得分:0)

您可以使用array_count_values(),check the live demo

<?php

$shippingtimearr = array("", "1630", "1530", "1530", "1530", "", "");
print_r(array_count_values($shippingtimearr)['']);

答案 3 :(得分:0)

由于似乎没有人完全明白我在寻找什么,我会发布一个解决方案,我自己使用&#34;而#34;循环:

$counter = 0;
$shippingtimearr = ["", "1630", "1530", "1530", "1530", "", ""];
$start = 3;

while ($shippingtimearr[$start++] == NULL) {
    ++$counter;
    if ($start > 6) $start = 0;
}