将字符串推入空数组会发出警告

时间:2014-04-09 10:26:00

标签: php

我创建了空数组并将val推入其中。

$var  = array();
function printTag($tags) {
        foreach($tags as $t) {
                echo $t['token'] . "/" . $t['tag'] .  " ";
                if($t['tag'] == 'NN' OR $t['tag']== 'JJ'){
                        array_push($var, $t['token'])   ;
                }
        }
        echo "\n";
}

代码对我来说很好但是给出了错误:

 array_push() expects parameter 1 to be array, null given in /var/www/html/postag/poscall.php on line 9

这里有什么问题?

整个代码:

<?php
// little helper function to print the results
include ("postag.php");
$var  = array();
function printTag($tags) {
        foreach($tags as $t) {
                echo $t['token'] . "/" . $t['tag'] .  " ";
                if($t['tag'] == 'NN' OR $t['tag']== 'JJ'){
                        array_push($var, $t['token'])   ;
                }
        }
        echo "\n";
}

$tagger = new PosTagger('lexicon.txt');
$tags = $tagger->tag('The quick brown fox jumped over the lazy dog. this is really yummy and excellent pizza I have seen have really in love it it');
printTag($tags);
?>

2 个答案:

答案 0 :(得分:1)

你的$ var = array();语句超出了函数范围,超出了函数的范围。把它放在函数内部,它将删除警告

function printTag($tags) {
   $var  = array();
   foreach($tags as $t) {
            echo $t['token'] . "/" . $t['tag'] .  " ";
            if($t['tag'] == 'NN' OR $t['tag']== 'JJ'){
                    array_push($var, $t['token'])   ;
            }
    }
    echo "\n";
}

答案 1 :(得分:1)

你的问题是$var不属于你的函数范围,所以它被隐式声明为null(这也引起了注意)。

那就是说,这似乎是一个很好的案例array_reduce()

$var = array_reduce($tags, function(&$result, $t) {
    if (in_array($t['tag'], ['NN', 'JJ'])) {
        $result[] = $t['token'];
    }
    // you could do some output here as well
    return $result;
}, []);

它同时过滤和映射,返回值是你想要的数组。

或者,只需在函数内声明$var并返回它:

function printTag(array $tags) 
{
    $var = [];

    foreach($tags as $t) {
        // ...
    }

    return $var;
}

// ...
$var = printTag($tags);