2017-02-24 73 views
-1

在這裏我有一個JSON,我向twitter API發出請求後得到。我已經看到了循環json的不同工作示例。即使我已經在另一個項目中做到了。但是這次它不起作用。循環JSON的問題

我測試了很多東西。我想這是正常的,現在不起作用。變量arrayFriends甚至沒有被使用。只是我正在測試一些動作。

不知道我失敗的確切位置。我想有一些反饋

謝謝你們!

$url = 'https://api.twitter.com/1.1/friends/ids.json'; 
$getfield = '?screen_name=J7mb0'; 
$requestMethod = 'GET'; 


$twitter = new TwitterAPIExchange($settings); 
$json = $twitter->setGetfield($getfield) 
->buildOauth($url, $requestMethod) 
->performRequest(true, array(CURLOPT_CAINFO => dirname(__FILE__) . '/cacert.pem')); 
echo $twitter->setGetfield($getfield) 
->buildOauth($url, $requestMethod) 
->performRequest(true, array(CURLOPT_CAINFO => dirname(__FILE__) . '/cacert.pem')); 



$arrayFriends = var_dump(json_decode($json, true, 512, JSON_BIGINT_AS_STRING)); 

$json = json_decode($json, true); 

echo $json; 

foreach($json->ids as $obj){ 
    echo $obj->ids; 

} 

回答

1

如果您使用json_decodetrue,返回值將是一個數組,不是對象。 因此,您將無法使用這裏的屬性的訪問方法:

foreach($json->ids as $obj){ 

你必須使用,而不是數組訪問方法:

foreach($json['ids'] as $obj){ 

,或者在解碼改變參數,所以你得到一個對象:

$json = json_decode($json, false); 
// or just simply: 
// $json = json_decode($json); 
// since the second parameter defaults to FALSE 

此外,$arrayFriends將保持爲空,因爲後續代碼var_dump 返回任何在所有。

// Change this: 
// $arrayFriends = var_dump(json_decode($json, true, 512, JSON_BIGINT_AS_STRING)); 
// ...to this: 
$arrayFriends = json_decode($json, true); 
0

它的工作!嘗試不同的事情後,它開始工作。

其實我試圖訪問另一個JSON,但這是行不通的。這是相同的應用程序,但更多的內容。

$user = 'seyroku'; 

$url = 'https://api.twitter.com/1.1/friends/ids.json'; 
$getfield = '?screen_name='.$user.''; 
$requestMethod = 'GET'; 


$twitter = new TwitterAPIExchange($settings); 
$json = $twitter->setGetfield($getfield) 
->buildOauth($url, $requestMethod) 
->performRequest(true, array(CURLOPT_CAINFO => dirname(__FILE__) . '/cacert.pem')); 



$arrayFriends = json_decode($json, true,512,JSON_BIGINT_AS_STRING); 

foreach($arrayFriends['ids'] as $obj){ 
    echo $obj,","; 

$url2 = 'https://api.twitter.com/1.1/users/lookup.json'; 
$getfield2 = '?user_id='.$obj.''; 

$json2 = $twitter->setGetfield($getfield2) 
->buildOauth($url2, $requestMethod) 
->performRequest(true, array(CURLOPT_CAINFO => dirname(__FILE__) . '/cacert.pem')); 

    echo $twitter->setGetfield($getfield2) 
->buildOauth($url2, $requestMethod) 
->performRequest(true, array(CURLOPT_CAINFO => dirname(__FILE__) . '/cacert.pem')); 

    $json3 = json_decode($json2, true); 

    foreach ($json3['name'] as $nombre) { 
     echo $nombre,","; 
    } 


    /* $sql = "INSERT INTO friendtest (user, friends) 
VALUES ('$user' , '$obj')"; 

if (mysqli_query($conn, $sql)) { 
    echo "New record created successfully"; 
} else { 
    echo "Error: " . $sql . "<br>" . mysqli_error($conn); 
}*/ 

} 

第一個爲每個它正確地返回我的身份證。但是我期望給我的那個ID的第二個名字並沒有這樣做。我嘗試了不同的東西,但仍然無法正常工作。

你能給我一些反饋嗎?

對不起,這傢伙太糟糕了。