PHP-cURL在函数中向数组添加条目不起作用

时间:2014-10-08 20:16:19

标签: php arrays function curl

我可以回复我在函数request_callback中得到的响应,所以我认为将响应保存到数组associative_array []是微不足道的,但是这只会产生单个条目,就像每个条目后数组被擦除一样。 / p>

我使用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();


?>

2 个答案:

答案 0 :(得分: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";
}

答案 1 :(得分: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";
}