在另一个PHP文档中获取变量集

时间:2014-11-23 16:43:05

标签: php arrays function variables

好吧所以我试着在我的index.php上调用一个函数来调用misc.php上的一个函数。 misc.php上的函数在auction-loop.php上使用了一个数组,但它返回就好像变量未定义一样。

这是我的auction-loop.php的样子,

<?php
$auctions = array();
$row = array();
$sqlquery = "SELECT * FROM auctions";
if ($result = $db->query($sqlquery)) {
    while ($row = $result->fetch_assoc()) {
        $auctions[$row['id']]['id'] = $row['id'];
        $auctions[$row['id']]['title'] = $row['title'];
        $auctions[$row['id']]['featured_image'] = $row['featured_image'];
        $auctions[$row['id']]['description'] = $row['description'];
        $auctions[$row['id']]['date'] = $row['date'];
        $auctions[$row['id']]['location'] = $row['location'];
        $auctions[$row['id']]['highlights'] = $row['highlights'];
        $auctions[$row['id']]['catagories'] = $row['catagories'];
        $auctions[$row['id']]['notes'] = $row['notes'];
        $auctions[$row['id']]['terms'] = $row['terms'];
        $auctions[$row['id']]['contact'] = $row['contact'];
    }
}
?>

这是misc.php,

<?php
function auction_title($auction_id){
    echo $auctions[$auction_id]['title'];
}
?>

最后,在index.php上调用函数,

include_once ('parts/connections/connection.php'); 
include_once ('parts/staticfiles/auction-loop.php');
include_once ('parts/staticfiles/misc.php'); 
<?php auction_title(1); ?>

所有这些,它正在吐出错误,

  

注意:未定义的变量:第8行的D:\ xampp \ htdocs \ parts \ staticfiles \ misc.php中的拍卖

数组是否在auction-loop.php上设置,而不是将其设为misc。 提前致谢! :)

2 个答案:

答案 0 :(得分:2)

您没有将$ auction变量发送到auction_title()函数。如果你想住在2005年,你可以放     auction_title()函数中的全球$ auction。 或者,处理它的更好方法是重新定义函数以接受两个参数。

function auction_title($auctions=array(),$auction_id=0){

    if (!empty($auctions) && isset($auctions[$auction_id])){
       return $auctions[$auction_id]['title'];
    }

} 

希望有所帮助。

答案 1 :(得分:1)

您必须告诉function auction_title它将使用global $auctions变量。

function auction_title($auction_id) {
  global $auctions;
  echo $auctions[$auction_id]['title'];
}