有条件地添加到数组

时间:2018-08-06 15:35:30

标签: php arrays if-statement

我正在尝试在IF条件下添加到数组,但是尽管我处于foreach循环中,但它没有追加

我没有附加到$ connected上,但是密钥增加了:

$key1 = '0';
foreach ($dataNewAndUnlock1 as $key => $val) {
    $stream = ssh2_exec($connection, 'ping -c 1 '. $val);

    stream_set_blocking($stream, true);

    while ($o = fgets($stream)) {
        $connected = array();

        if (strpos($o, 'ttl') !== false) {
            $connected[$key1] = $val;

            echo $val .' EnodeB is connected <br>';
            $key1++;
        }

        if (strpos($o, '0 received') !== false) {
            echo $val .' EnodeB NOT connected <br>';
        }
    }
}

$ connnected给出这样的内容,然后var_dump最后为空

C:\wamp64\www\SendJason2.php:286:
array (size=1)
  0 => string 'XXX.XX.XXX.XXX' (length=14)
C:\wamp64\www\SendJason2.php:286:
array (size=1)
  1 => string 'XXX.XX.XXX.XX' (length=13)
C:\wamp64\www\SendJason2.php:286:
array (size=1)
  2 => string 'XXX.XX.XXX.XXX' (length=14)
C:\wamp64\www\SendJason2.php:286:
array (size=1)
  3 => string 'XXX.XX.XXX.XXX' (length=14)
C:\wamp64\www\SendJason2.php:286:
array (size=1)
  4 => string 'XXX.XX.XXX.XXX' (length=14)
...

C:\wamp64\www\SendJason2.php:306:
array (size=0)
  empty

1 个答案:

答案 0 :(得分:4)

每次$connected循环迭代时,您都用一个空数组覆盖foreach。将$connected的分配移到foreach循环之前。

$key1 = '0';
$connected = array();
foreach ($dataNewAndUnlock1 as $key => $val) {
    ...

此外,要追加到数组,您不需要维护自己的索引,只需使用以下语法即可:

$connected[] = $val;