php损失和foreach中的变量范围

时间:2014-04-30 18:07:05

标签: php arrays

我有一些代码。当我尝试返回$ language [0] =>一切正常。但是当我尝试返回$ language [1] =>这个元素找不到。请告诉我如何更改此代码

function language($id)
{
            $language = array();
            $criteria = array("id" => $id);
            $fields = array('language');

            $cursor = $collection->find($criteria, $fields);

            foreach ($cursor as $row) {
                $language[0] = $row['language'];

            }


            $criteria = array("id" => $language[0]);
            $fields = array('lang');

            $cursor2 = $collection->find($criteria, $fields);
            foreach ($cursor2 as $row) {
                $language[1] = $row['lang'];
            }
            return $language[1];
}

1 个答案:

答案 0 :(得分:0)

删除[0]

$language[0] = $row['language'];  // overwritting subscript 0

所以它变成

$language[] = $row['language']; // adding to index

此外,$collection未定义。