doujia7779 2018-08-14 18:45
浏览 150
已采纳

PHP可以轻松地将数组结构化为单个变量以传递给函数

Say I have a PHP array like this.

array(2) { ["page"]=> string(1) "a" ["subpage"]=> string(4) "gaga" }

I want to pass the contents of this array to a function call, of a function like this:

function doStuff($page, $subpage) {
 // Do stuff
}

How could I destructure this array into individual objects to pass to the function? The variables of the function will always be in the same order that the corresponding keys are in the array.

  • 写回答

3条回答 默认 最新

  • dongya6997 2018-08-14 18:48
    关注

    You can use array_values to get the values out of the array and then call_user_func_array to call your function using an array of values as an argument.

    <?php
    $input = array( 'page' => 'a', 'subpage' => 'gaga' );
    $values = array_values($input);
    $result = call_user_func_array('doStuff', $values);
    

    Or, in newer versions of PHP (>=5.6.x), you can use argument unpacking with the ... operator:

    <?php
    $input = array( 'page' => 'a', 'subpage' => 'gaga' );
    $values = array_values($input);
    $result = doStuff(...$values);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元