douchuo9476 2018-04-05 00:19
浏览 65
已采纳

数组内的数组到Object

after using this code to send params through ajax:

 paramsToSend = $form.serializeArray();
 params = JSON.stringify(paramsToSend)

I got this array after decode json on serverside:

 Array
 (
    [0] => Array
      (
        [name] => name
        [value] => Naomi
      )

    [1] => Array
      (
        [name]  => password
        [value] => test123456
      )

[2] => Array
    (
        [name] => email
        [value] => naomitest@gmail.com
    )

[3] => Array
    (
        [name] => code
        [value] => test123456@test123456
    )

[4] => Array
    (
        [name]  => phone
        [value] => 423523545435
    )

)
  1. Can I convert it to Object and get value like this:

    User.name //will print Naomi
    User.password // will print test123456
    

Because I need other different params for ajax call, is the way I serializeArray data + convert to json best practices? If not please give me advice. Thanks

  • 写回答

1条回答 默认 最新

  • dongshan6870 2018-04-05 00:30
    关注

    For this one you can use array_column to pull out the keys and values, then array_combine to combine them into a key/value array, then use ArrayObject to make it an array or object.

    For example:

    <?php
    $data = [
        ['name' => 'name', 'value' => 'Naomi'],
        ['name' => 'password', 'value' => 'test123456'],
        ['name' => 'email', 'value' => 'naomitest@gmail.com'],
        ['name' => 'code', 'value' => 'test123456@test123456'],
        ['name' => 'phone', 'value' => 423523545435]
    ];
    
    $data = new ArrayObject(
        array_combine(
            array_column($data, 'name'),
            array_column($data, 'value')
        )
    );
    $data->setFlags(ArrayObject::STD_PROP_LIST|ArrayObject::ARRAY_AS_PROPS);
    
    echo $data->name; // Naomi
    echo $data['name']; // Naomi
    

    https://3v4l.org/oBbd0

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题