2014-10-08 35 views
0

我可以在函數request_callback中迴應我剛剛好的響應,所以我認爲將響應保存到數組associative_array []中很簡單,但是這隻會導致單個條目,例如數組在每次輸入後都會被擦除。PHP-cURL添加條目到一個不起作用的函數中的數組

我利用https://github.com/LionsAd/rolling-curl/blob/master/RollingCurl.php

<?php 
# Get the all the items numbers 
$url1 = "http://api.guildwars2.com/v2/commerce/listings"; 
$response1 = file_get_contents($url1); 
$data1 = json_decode($response1, true); 

#retrieve item names and link with numbers 
function request_callback($response) { 
    $temporary_array = json_decode($response, true); 
    $associative_array[] = array('name' => $temporary_array['name'],'id' => $temporary_array['id']); 
    // array[] places the new entry at end of urls stack, faster then array_push($array, new entry); 
    print_r ($associative_array); 
    echo "\n"; 
} 

# Multiple curl request 
require("rollingcurl.php"); 

for ($x=0;$x<5;$x++){ 
     $itemurl1 = "http://api.guildwars2.com/v2/items/{$data1[$x]}"; 
     $urls[$x]= $itemurl1; 
    } 
$rc = new RollingCurl("request_callback"); 
$rc->window_size = 20; 
foreach ($urls as $url) { 
    $request = new RollingCurlRequest ($url) ; 
    $rc -> add ($request) ; 
} 
$rc->execute(); 


?> 
+0

'$ urls'從哪裏來?你可以發佈它的'var_dump'嗎? – Machavity 2014-10-08 20:21:09

+0

初學者錯誤嘗試並行下載所有數據。尊重服務器 – 2014-10-08 20:22:15

回答

0

你的數組是本地的你的函數,因此重置每個調用。 嘗試添加全局聲明,你會得到你所期望的(所有的值);

function request_callback($response) { 
    global $associative_array; 
    $temporary_array = json_decode($response, true); 
    $associative_array[] = array('name' => $temporary_array['name'],'id' => $temporary_array['id']); 
    // array[] places the new entry at end of urls stack, faster then array_push($array, new entry); 
    print_r ($associative_array); 
    echo "\n"; 
} 
+0

現在感謝您添加數組條目!但我認爲我在搜索時一直在閱讀全球化是不好的做法? – Singul4r1ty 2014-10-08 20:35:26

0

我創建功能之外的陣列。看起來你正在每個函數調用中創建一個新的數組。

$associative_array = array(); 
function request_callback($response) { 
     global $associative_array; 
     $temporary_array = json_decode($response, true); 
     $associative_array[] = array('name' => $temporary_array['name'],'id' => $temporary_array['id']); 
     // array[] places the new entry at end of urls stack, faster then array_push($array, new entry); 
     print_r ($associative_array); 
     echo "\n"; 
} 
相關問題