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

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

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效