【问题标题】:Cannot get PHP function to re-run and update array无法让 PHP 函数重新运行和更新数组
【发布时间】:2017-08-02 15:25:27
【问题描述】:

我的 PHP 代码如下所示:

$size=1;
$newoffset=0;
$final=[];

function runQuery()
{
    global $newoffset;
    global $size;
    global $final;
    $SECRET_KEY = 'XXX';
    $s = hash_hmac('sha256','/api/v2/tags?limit=100&offset='.$newoffset.'-', $SECRET_KEY, false);
    $curl = curl_init();
    $headers = array();
    $headers[] = 'Accept: application/json';
    $headers[] = 'Content-Type: application/json';
    $headers[] = "RT-ORG-APP-CLIENT-ID: XXX";
    $headers[] = "RT-ORG-APP-HMAC: ". $s;
    curl_setopt_array($curl, array(
                  CURLOPT_URL => 'api/v2/tags?limit=100&offset='.$newoffset,
                  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                  CURLOPT_CUSTOMREQUEST => "GET",
                  CURLOPT_RETURNTRANSFER => true,
                  CURLOPT_HTTPHEADER => $headers,
                ));
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);
    if ($err) {
        echo "cURL Error #:" . $err;
    } else {
        $array = json_decode( $response, true );
        $results = $array['data'];
        //print_r($results); This returns correctly
        $size = sizeof($array['data']); //size of array
        $result = array();

        if ($size>0){
            //print_r($results); This also returns correctly
            $newoffset += 100;
            foreach($results as $member) {
                $result[] = array(
                        'tag_name' => $member['name'],
                        'tag_id' => $member['id'],
                        'tag_public_id' => $member['public_id'],
                    );
            }
            $final['all_tags'] = $result;
        }
    }
}//end function

if($size>0){
    runQuery();
}else{
    echo json_encode($final);
}

这应该做的是运行curl,如果它返回结果,则将这些结果推送到$final。如果有结果,则增加变量(newoffset)的值,以便在 curl 请求中使用。这是因为我一次只能获得 100 个结果,并且需要尽可能多地执行offset 才能获得所有结果。

如果返回的大小为 0,则停止并回显结果。

但是,这不会返回任何内容。

我在想我有一个全局变量问题。

请注意,如果我删除所有条件和函数,我知道查询有效,所以这不是问题。

关于如何修复的任何建议?

【问题讨论】:

  • 我建议您从格式化代码开始。
  • 一些合理的代码缩进是个好主意。它可以帮助我们阅读代码,更重要的是,它将帮助 您调试代码 Take a quick look at a coding standard 为您自己谋福利。您可能会被要求在几周/几个月内修改此代码,最后您会感谢我的。
  • 真的吗?在我看来不像它
  • @jonmrich ME,你改变了一行的缩进。
  • 无循环运行 5 或 6 次?

标签: php arrays curl


【解决方案1】:

您的runQuery 函数只运行一次,因为您只调用了一次。执行不会在函数声明结束的那一行继续,它会从调用函数的地方继续,在你的情况下是脚本的结尾。

你必须移动

if($size>0){
    runQuery();
}else{
    echo json_encode($final);
}

加入函数并调用一次runQuery

此外,不鼓励使用全局变量,因为它可能会导致与其他代码发生冲突。最好使用函数参数和返回值。

【讨论】:

  • 谢谢...这是有道理的。如果我这样做,我只会得到函数的最后一次运行。
  • 其实这没什么意义
  • @RiggsFolly 那你有什么建议吗?
  • 对不起,我要去开会了。
  • 它只返回最后一次运行,因为每次运行都会覆盖$final['all_tags']。在 foreach 循环中将 $result[] 替换为 $final['all_tags'][]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-11
  • 2021-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多