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));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R
  • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法
  • ¥15 八路抢答器设计出现故障
  • ¥15 opencv 无法读取视频
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档