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 PdfiumViewer pdf转图片
  • ¥15 利用Java连接API接口总是出问题
  • ¥15 请教一个关于镜头标定,棋盘格格子大小的问题(畸变测试)
  • ¥15 安装GroudingDINO RuntimeError: Error compiling objects for extension
  • ¥15 关于推送项目到github的问题
  • ¥15 急!C++指针编写相关的问题
  • ¥15 kerberos身份认证配置问题
  • ¥30 用python写一个多签情况下波场的代理资源和回收资源
  • ¥15 matlab学期例题代码答疑
  • ¥15 在线手电筒追加按钮JS