gpt4 book ai didi

php - 如何在 symfony2 中将 json 转换为 php 对象?

转载 作者:可可西里 更新时间:2023-11-01 13:23:21 27 4
gpt4 key购买 nike

通过 jquery,我使用 ajax/POST 这个 json

{"indices":[1,2,6]}:

到 symfony2 Action 。现在我只真正关心数组,所以如果这使事情变得容易得多,我也可以发布 [1,2,6]。

如何将其转换为 php 对象?


不知何故,这不起作用:

/**
* @Route("/admin/page/applySortIndex", name="page_applysortindex")
* @Method("post")
* @Template()
*/
public function applySortIndexAction()
{
$request = $this->getRequest();
$j = json_decode($request->request->get('json'));
$indices = $j->indices;
return array('data'=> $indices);
}

给出一个

注意:试图在 .../PageController.php 第 64 行(500 内部服务器错误)中获取非对象的属性

这将是我访问 $j->indices 的地方,其中 $j 似乎为空


海报:

$.ajax({
type: 'POST',
url: "{{ path('page_applysortindex')}}",
data: $.toJSON({indices: newOrder}),
success: ...

最佳答案

获取通过正文发送的数据:

$request = $this->getRequest();
$request->getContent();

检查输出然后采取行动。但这将包含 json。

(是的,测试过它。这会导致您的 json)


从 Controller 中获取名称为 json 的 POST 参数:

$request = $this->getRequest();
$request->request->get('json');

Request-object


$j = json_decode('{"indices":[1,2,6]}');

var_dump($j);

导致:

object(stdClass)#1 (1) {
["indices"]=>
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(6)
}
}

关于php - 如何在 symfony2 中将 json 转换为 php 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7360417/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com