[英]Array inside array to Object
after using this code to send params through ajax: 使用以下代码通过ajax发送参数后:
paramsToSend = $form.serializeArray();
params = JSON.stringify(paramsToSend)
I got this array after decode json on serverside: 我在服务器端解码json后得到了这个数组:
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
)
)
Can I convert it to Object and get value like this: 我可以将其转换为Object并获得如下值:
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? 因为我需要其他不同的参数来进行Ajax调用,所以我serializeArray数据+转换为json最佳实践的方式是吗? If not please give me advice. 如果没有,请给我建议。 Thanks 谢谢
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. 为此,您可以使用array_column提取键和值,然后使用array_combine将它们组合为键/值数组,然后使用ArrayObject使其成为数组或对象。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.