laravel 解码laravel 4 Input::json()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23327169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Decode laravel 4 Input::json()
提问by sh0umik
I am having a hard time decoding json input in laravel .. am building a Restful API and when i send post data using RestClient and then die and dump in laravel i got
我很难在 laravel 中解码 json 输入……我正在构建一个 Restful API,当我使用 RestClient 发送发布数据然后死掉并在 laravel 中转储时,我得到了
object(Symfony\Component\HttpFoundation\ParameterBag)#205 (1) {
["parameters":protected]=>
array(6) {
["firstName"]=>
string(8) "John"
["lastName"]=>
string(7) "Doe"
["bloodGroup"]=>
string(2) "B+"
["phone"]=>
string(8) "+9999999"
["address"]=>
string(8) "Somecity"
["symptoms"]=>
string(3) "Bla"
}
}
Now i have tied to access the data using
现在我已经绑定使用访问数据
$data = Input::json();
echo $data->firstName;
that does not work .. tried to convert it to array and then access
like $data['firstName']
does not work .
这不起作用..试图将其转换为数组,然后像访问一样$data['firstName']
不起作用。
array(1) {
["*parameters"] =>
array(6) {
["firstName"]=>
string(8) "John"
["lastName"]=>
string(7) "Doe"
["bloodGroup"]=>
string(2) "B+"
["phone"]=>
string(8) "+9999999"
["address"]=>
string(8) "Somecity"
["symptoms"]=>
string(3) "Bla"
}
}
i want to decode the data then save it to db, Here is a tutorial building similar App ..
我想解码数据然后将其保存到数据库,这是一个构建类似应用程序的教程..
I have tried the post_index() method explained here but no luck .
我已经尝试过这里解释的 post_index() 方法,但没有运气。
http://maxoffsky.com/maxoffsky-blog/building-restful-api-in-laravel-part-2-design-api-controller/
http://maxoffsky.com/maxoffsky-blog/building-restful-api-in-laravel-part-2-design-api-controller/
回答by Marwelln
You can use ->get()
to access properties from a Symfony\Component\HttpFoundation\ParameterBag
response.
您可以使用->get()
从Symfony\Component\HttpFoundation\ParameterBag
响应访问属性。
$input = Input::json();
$input->get('firstName')
You can also get all inputs as an array and then type cast it to an object with (object)
. Note that this will throw an error if your property doesn't exists, so if I where you, I would use the ->get()
method mentioned above.
您还可以将所有输入作为数组获取,然后将其类型转换为带有(object)
. 请注意,如果您的属性不存在,这将引发错误,因此如果我在您所在的位置,我将使用上述->get()
方法。
$input = (object)Input::all();
$input->firstName;
回答by Dean Chiu
Based on my experiment
根据我的实验
If you are sending an array of multiple objects like the following example from the Javascript using JSON
如果您使用 JSON 从 Javascript 发送多个对象的数组,如下例所示
[{crop_id: 1, test_id: 6},{crop_id: 1, test_id: 7},{crop_id: 1, test_id: 8}]
You need to use Input::json()->all()function in PHP.
你需要在 PHP 中使用Input::json()->all()函数。
$arr = Input::json()->all();
$crop_id = $arr[0]['crop_id'];
$test_id = $arr[0]['test_id'];