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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?