我尝试将多个元素添加到数组中(在本例中为$ allCats为example1和test1),但仍然不起作用:(有人可以向我解释我的错误吗?还是我做错了什么?
function getCats($Catlist, $name) {
$regex = '('.implode('|', $Catlist).')';
$success = preg_match_all($regex, $name, $matches);
return $success ? $matches[0] : [];
}
function Cats($name, $wrongCatlist, $allCats, $Catlist) {
$Cats = getCats($Catlist, $name);
$Cats2 = array_unique ( $Cats );
$Cats3 = '"'.implode('", "', $Cats2).'"';
array_push($allCats, $Cats3);
}
$name = "adidas example1 handschuhe test1 nike";
$wrongCatlist = [
];
global $allCats;
$allCats = [
];
$Catlist = [
"example1",
"test1"
];
Cats($name, $wrongCatlist, $allCats, $Catlist);
$allCats2 = ''.implode(', ', $allCats).'';
echo $allCats2;
答案 0 :(得分:1)
在PHP数组中按值传递。由于您要更新数组this
,因此该变量应通过引用传递。为此,您的函数定义将是:
_this
由于按引用传递有时会导致混淆,因此应在函数中使用return语句。然后该函数及其调用将发生如下变化:
$allCats