dongwei6457 2016-06-10 22:37
浏览 139
已采纳

如何将数组的所有元素(未知长度)作为单独的参数传递给函数? [重复]

This question already has an answer here:

I have an array in PHP which may contain data such as this:

$data = array("Apples", "Oranges", "Grapes", "Pears");

I then want to pass these values into the mysqli bind_param function. For this example it would look like this:

$stmt->bind_param("ssss", $data[0], $data[1], $data[2], $data[3]);

My question is how can I produce the same results as above if the length of the array is unknown? For example it may be five, ten or 15 elements long.

</div>
  • 写回答

1条回答 默认 最新

  • dpziir0079 2016-06-10 22:43
    关注

    With PHP 5.6 or higher:

    $stmt->bind_param(str_repeat("s", count($data)), ...$data);
    

    With PHP 5.5 or lower you might (and I did) expect the following to work:

    call_user_func_array(
        array($stmt, "bind_param"),
        array_merge(array(str_repeat("s", count($data))), $data));
    

    ...but mysqli_stmt::bind_param expects its parameters to be references whereas this passes a list of values (thanks Barmar for pointing this out).

    You can work around this (although it's an ugly workaround) by first creating an array of references to the original array.

    $references_to_data = array();
    foreach ($data as &$reference) { $references_to_data[] = &$reference; }
    unset($reference);
    call_user_func_array(
        array($stmt, "bind_param"),
        array_merge(array(str_repeat("s", count($data))), $references_to_data));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在不同的执行界面调用同一个页面
  • ¥20 基于51单片机的数字频率计
  • ¥50 M3T长焦相机如何标定以及正射影像拼接问题
  • ¥15 keepalived的虚拟VIP地址 ping -s 发包测试,只能通过1472字节以下的数据包(相关搜索:静态路由)
  • ¥20 关于#stm32#的问题:STM32串口发送问题,偶校验(even),发送5A 41 FB 20.烧录程序后发现串口助手读到的是5A 41 7B A0
  • ¥15 C++map释放不掉
  • ¥15 Mabatis查询数据
  • ¥15 想知道lingo目标函数中求和公式上标是变量情况如何求解
  • ¥15 关于E22-400T22S的LORA模块的通信问题
  • ¥15 求用二阶有源低通滤波将3khz方波转为正弦波的电路