无法分离返回的JSON输出以将其转换为新的PHP变量

时间:2015-08-03 22:06:57

标签: php json api

此问题已在其他地方以特定方式得到解答,但我需要制定一般规则/方法从API POST中获取人员ID,然后使用该规则/方法将新创建的人员移动到另一个区域该网站。

$timestamp = date("y-d-m G:i:s");

$client = new http\Client;
$request = new http\Client\Request;

$body = new http\Message\Body;
$body->addForm(array(
  'name' => $_POST['email'],
  'email' => $_POST['email'],
  'page-location' => $_POST['page-location'],
  'active_flag' => '1',
  'add_time' => $timestamp
), NULL);

$request->setRequestUrl('https://api.pipedrive.com/v1/persons');
$request->setRequestMethod('POST'); 
$request->setBody($body);

$request->setQuery(new http\QueryString(array(
  'api_token' => '472320163fd56c5371797bd54b91e7e5b04cd7a9'
)));

$client->enqueue($request)->send();
$response = $client->getResponse();


echo $response->getBody();

JSON返回如下内容:

{"success":true,"data":{"id":20,"company_id":506319,"owner_id":{"id":709354,"name":"Christian Bahrendt","email":"cb@nowdiscover.co","has_pic":true,"pic_hash":"41678d0bdf1124ecc6a88b01ffb360a7","active_flag":true,"value":709354},"org_id":null,"name":"tester@tester.com","first_name":"tester@tester.com","last_name":null,"open_deals_count":0,"closed_deals_count":null,"participant_open_deals_count":0,"email_messages_count":0,"activities_count":null,"done_activities_count":null,"undone_activities_count":null,"reference_activities_count":null,"files_count":null,"notes_count":0,"followers_count":0,"won_deals_count":0,"lost_deals_count":0,"active_flag":true,"phone":[{"value":"","primary":true}],"email":[{"label":"","value":"tester@tester.com","primary":true}],"first_char":"t","update_time":"2015-08-03 21:57:10","add_time":"2015-03-08 23:57:09","visible_to":"3","picture_id":null,"next_activity_date":null,"next_activity_time":null,"next_activity_id":null,"last_activity_id":null,"last_activity_date":null,"org_name":null,"cc_email":"nowdiscovergmbh@pipedrivemail.com","owner_name":"Christian Bahrendt"},"related_objects":{"user":{"709354":{"id":709354,"name":"Christian Bahrendt","email":"cb@nowdiscover.co","has_pic":true,"pic_hash":"41678d0bdf1124ecc6a88b01ffb360a7","active_flag":true}}}}

我需要将ID转换为$ newUserID。

我将如何/应该在PHP中做到这一点??

1 个答案:

答案 0 :(得分:0)

如果您想轻松访问 JSON 中的数据,则需要使用 json_decode http://php.net/manual/en/function.json-decode.php)将其解码为对象或关联数组,然后像往常一样访问对象/数组中的数据:

<!DOCTYPE html>
<html>
<head>
<script>
var valChange = function(val) { 
    switch(val){
        case "one":
            window.location = "http://google.com"
            break;
        case "two":
            window.location = "http://facebook.com"
            break;
        case "three":
            window.location = "http://stackoverflow.com"
            break;  
    }
};
</script>
</head>
<body>
    <select onchange="valChange(this.value)">
        <option selected disabled>Choose</option>
        <option value="one">One</option>
        <option value="two">Two</option>
        <option value="three">Three</option>
    </select>
</body>
</html>