我实际上是Api世界的新手,我正在研究使用卷曲请求获取和发回数据的Api。在获取时,传递以下信息
{"posts":{"userinfo":{"fullname":"Precious Tom","user_name":"Kendrick","email":"tomprezine@gmail.com","gender":"Male","country":"Nigeria","city":"Port Harcourt","state":"Rivers","year":"1997","month":"9","day":"6"}}}
内容类型:text / html;字符集= UTF-8
http代码:200
拆分阵列似乎是我的问题,如果以前曾经问过这个问题,我很抱歉,但是,我需要你的帮助。 感谢。
更多信息,这是我的卷曲请求
<?php
session_start();
# data to be sent
$data = array(
'public_key' => 'pk_test_3gc9ffb0hccggf5f3b4e258da848343dff4ae900',
'app_name' => 'Circlepanda',
'app_id' => '2147483647'
);
$curl = curl_init();
# you can also set the url you wanna communicate with by setting
# $curl = curl_init('http://localhost/circlepanda');
# We post Data
curl_setopt($curl, CURLOPT_POST, 1);
# Set the url path we want to call
curl_setopt($curl, CURLOPT_URL, 'http://localhost:8888/circlepanda/api/userinfo');
# Make it so the data coming back is put into a string
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
# You can also bunch the above commands into an array if you choose using: curl_setopt_array
# Send the request
$result = curl_exec($curl);
# Get some cURL session information back
$info = curl_getinfo($curl);
echo '<br> content type: ' . $info['content_type'] . '<br>';echo 'http code: ' . $info['http_code'] . '<br>';
# Free up the resources $curl is using
curl_close($curl);
?>
我将传递一个Variable而不是一个直接数组。 尝试直接数组你的代码运行正常,传递变量毛刺,它停止工作......
答案 0 :(得分:1)
$city_names = json_decode('{"posts":{"userinfo":{"fullname":"Precious Tom","user_name":"Kendrick","email":"tomprezine@gmail.com","gender":"Male","country":"Nigeria","city":"Port Harcourt","state":"Rivers","year":"1997","month":"9","day":"6"}}}', true);
print_r($city_names);
ANS
Array
(
[posts] => Array
(
[userinfo] => Array
(
[fullname] => Precious Tom
[user_name] => Kendrick
[email] => tomprezine@gmail.com
[gender] => Male
[country] => Nigeria
[city] => Port Harcourt
[state] => Rivers
[year] => 1997
[month] => 9
[day] => 6
)
)
)
$city_names = json_decode($json, true);
print $arr['posts']['userinfo']['fullname'];
答案 1 :(得分:0)
你有两个选择:
1 - 使用以下内容将json
转换为object
$obj = json_decode($json);
print $obj->posts->userinfo->fullname;
2 - 使用以下内容将json
转换为array
$arr = json_decode($json, true);
print $arr['posts']['userinfo']['fullname'];
详细了解json_decode