PHP数组push在循环内不会改变循环外的数组


PHP Array push in loop doesn't change the array outside of the loop

我遇到了以下问题:

private function getMyThemeIds($collection){
    $result = [];
    ...
      foreach ($results as $doc) {
        file_put_contents('2.txt', $doc->getUnid()); //everything is fine here
        $result[] = $doc->getUnid();
        file_put_contents('3.txt', print_r($result,true)); //again, array is just fine, barely 4000 entries
      }
    file_put_contents('4.txt', print_r($result,true)); // but here we see what was in this array right after initialization. Nothing in this case.
    return $result;
  }

我尝试了不同的方法-将foreach改为for, $result[]改为array_push等,但无济于事。有人知道这可能是什么原因吗?

您可以使用'array()'初始化数组。请按照下面的语句初始化数组

$result = array();

初始化$result后,可以向其追加数据。您可以参考以下链接进行数组初始化http://www.w3schools.com/php/func_array.asp

详情请参见file_put_contents。你可以试试这个

private function getMyThemeIds($collection){
    $result = array();
    ...
      foreach ($results as $doc) {
        file_put_contents('2.txt', $doc->getUnid()); //everything is fine here
        $result[] = $doc->getUnid();
        file_put_contents('3.txt', serialize($result)); //again, array is just fine, barely 4000 entries
      }
    file_put_contents('4.txt', serialize($result)); // but here we see what was in this array right after initialization. Nothing in this case.
    return $result;
  }