dqwh26750 2015-09-02 06:35
浏览 107
已采纳

如何遍历数组并将每个元素作为参数传递给php中的构造函数

I want to loop through an array and get each element to pass as parameters to a constructor. here is my example

[user_by_province] => Array
    (
        [label] => Array
            (
                [0] => a
                [1] => b
                [2] => c
                [3] => d
                [4] => e
                [5] => f
            )

        [count] => Array
            (
                [0] => 2
                [1] => 1
                [2] => 1
                [3] => 1
                [4] => 7
                [5] => 1
            )

    )

Here is the constructor:

$pc = new C_PhpChartX(array(array('a','2'),
                            array('b','1'),
                            array('c','1'),
                            array('d','1'),
                            array('e','7'),
                            array('f','1')));

so how can i do that with php thanks for any help, may we can do that with array_map or no? thanks for any help

  • 写回答

4条回答 默认 最新

  • doutang3077 2015-09-02 07:14
    关注

    As you suggested array_map with multiple arguments could be a good solution.

    <?php
    
    $userByProvince = array(
        'label' => array('a', 'b', 'c', 'd', 'e', 'f'),
        'count' => array('1', '2', '3', '4', '5', '6'),
    );
    
    function combine($arg1, $arg2)
    {
        return array($arg1, $arg2);
    }
    
    $arguments = array_map('combine', $userByProvince['label'], $userByProvince['count']);
    
    $pc = new C_PhpChartX($arguments);
    

    If you are using PHP 5.3 you can even substitute the function with a lambda expression to make the code more compact (see docs).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 我下载图形界面重启完就变成这样了,打字也打不了,动也动不了,该怎么解决(操作系统-centos)
  • ¥15 VBA中在窗体中遍历所有checkbox控件,提取出被选中的checkbox的caption值
  • ¥15 在Ubuntu上有什么命令,或者是系统文件能告诉我链接nvme ssd的pcie槽位是不是支持热插拔功能?
  • ¥15 ansys license许可证问题
  • ¥20 QQ号和密码都能正常登录微信 QQ号和密码登录微信显示密码错误
  • ¥15 qiankun主应用注册子应用提示跨域
  • ¥15 单片机RTOS Kernel与应用分离开发,Kernel如何调起应用?
  • ¥15 快手小店商家版APP怎么第三方APP跳转到指定用户聊天界面
  • ¥15 为什么AVL fire软件仿真时的步长改变了,仿真结果也会改变
  • ¥100 如何帮我写一个java小游戏