如何使用数组作为函数的参数?

时间:2016-06-10 07:00:27

标签: php arrays function foreach

我想使用数组作为函数的参数。我希望这是有效的:

function data($array){
    $pdo = Database::connect(); 
    $sql = 'SELECT  *  FROM data ORDER BY id DESC';
    foreach ($pdo->query($sql) as $row) {
       $elements = implode($array);
       echo "Start> ".$elements. "<End";
    }
 }
 $array = array("$row['id']", "$row['name']", "$row['age']", "$someothervariable");      
 data($array);

但我的结果是:Start> <End

编辑:

像这样一切运作良好:

    $pdo = Database::connect(); 
    $sql = 'SELECT  *  FROM data ORDER BY id DESC';
    foreach ($pdo->query($sql) as $row) {
       echo $row['id'];
       echo $row['name'];
       echo $row['age'];
    }

3 个答案:

答案 0 :(得分:4)

不清楚你要做什么。也许你想要这个:

ini_set('display_errors', 1);
error_reporting(-1);

答案 1 :(得分:0)

function data($array){
    $pdo = Database::connect(); 
    $sql = 'SELECT  *  FROM data ORDER BY id DESC';
    foreach ($pdo->query($sql) as $row) {
       $elements = implode($array);
       echo $elements;
    } // this is end of foreach

} // you are missing this braces

 $array = array("$row['id']", "$row['name']", "$row['age']");      
 data($array);

工作示例:http://sandbox.onlinephpfunctions.com/code/20d306c8c7df9d4c446eebd34703a7fd68f76665

答案 2 :(得分:0)

试试这个:

function data(&$array){ // note the & sign.