如何在php

时间:2016-03-07 04:09:46

标签: php arrays

基本上,我有一个名为$userID = $_POST['userID'];的变量。现在,这只能取一个值。

但我希望它尽可能采用多个值,例如$userID = 1,2,4,5$userID = 2甚至$userID = 1,2,3,4,5,6,7

我不知道如何为多个号码执行此操作,但这是我的php脚本:

<?php
    require "init.php";
function foo()
{
    $numargs = func_num_args();
    echo "Number of arguments: $numargs \n";
    if ($numargs >= 2) {
        echo "Second argument is: " . func_get_arg(1) . "\n";
    }
    $arg_list = func_get_args();
    for ($i = 0; $i < $numargs; $i++) {
        echo "Argument $i is: " . $arg_list[$i] . "\n";
    }
}
    if(!empty($_POST['userID'])){
        $userID = $_POST['userID']; 
        $userID = foo($userID);
        $stmt = "SELECT userID, forename, surname, email, age
                FROM users
                WHERE userID IN (?)";   
        $result = $conn-> prepare($stmt);
        $result->bind_param('i', $userID);
        $result->execute(); 
        $outcome=$result->get_result();
        $response = array();
        if(($outcome->num_rows)>0){
            while($row = $outcome->fetch_assoc()){
                $response[] = array
                (
                    "userID" => $row["userID"],
                    "forename" => $row["forename"],
                    "surname" => $row["surname"],
                    "email" => $row["email"],
                    "age" => $row["age"]
                );
            }
        echo json_encode($response); 
        }
        else{
            echo json_encode("None found");
        }
    }

    ?>
编辑:使用上面的代码,我不断得到: Number of arguments: 1 Argument 0 is: 1,2,3 "Failed" - 如果$userID = 1,2,3

因此,您可以看到userID只能获取1个值,但我想在某些情况下采用多个。如何转换它以便需要很多。

这是我坚持的唯一一点,因为当我为SQL提供硬编码值时phpmyadmin内容的其余部分正常工作

1 个答案:

答案 0 :(得分:0)

您可以使用call-user-func-array

例如:

  $userID = "1,2,3,4,5,6,7";
  call-user-func-array(function_name, explode(',', $userID));

如果您使用的是php 5.6&gt;,那么您可以使用...可变参数函数。

Manual

根据你的评论,

您可以使用func_get_arg

修改示例

<?php
function foo()
{
    $numargs = func_num_args();
    echo "Number of arguments: $numargs \n";
    if ($numargs >= 2) {
        echo "Second argument is: " . func_get_arg(1) . "\n";
    }
    $arg_list = func_get_args();
    for ($i = 0; $i < $numargs; $i++) {
        echo "Argument $i is: " . $arg_list[$i] . "\n";
    }
}

foo($userID);
?>