收益率不返回值

Yield not returning value

我正在尝试调整此代码:

function pc_permute($items, $perms = array( )) {
    if (empty($items)) {
        echo implode($perms); // yield (implode($perms));
    }  else {
        for ($i = count($items) - 1; $i >= 0; --$i) {
             $newitems = $items;
             $newperms = $perms;
             list($foo) = array_splice($newitems, $i, 1);
             array_unshift($newperms, $foo);
             pc_permute($newitems, $newperms);
         }
    }
}

正如您在同一行中看到的那样,要获得收益。但是这样做returns没有价值。

我正在调用它:

  foreach (pc_permute($a) as $y) {
        echo $y;
  }

其中 $a 应该类似于 $a = [0,1,2];

使用 echo 有效,使用 yield 无效。我做错了什么?

您的递归调用忽略了产生的值。

因为 PHP 7 你可以使用 generator delegation (yield from):

yield from pc_permute($newitems, $newperms);

对于旧版本,只需编写一个产生每个结果的循环。