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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵