duanqiang3925 2016-11-30 06:35
浏览 168
已采纳

PHP - 循环POST值N次

I'm working with an API that sends a request to my server with some POST values, including this one:

'NumMedia' => '1'

The value for NumMedia determines how many additional parameters will be received. For example if NumMedia = 1 I will get 2 additional parameters like this:

'MediaContentType0' => 'image/jpeg'
'MediaUrl0' => 'https://api.server.com/2010-04-01/Accounts/xxxxxxxx',

If NumMedia is greater than 1 I'll get an additional set of parameters like this:

'MediaContentType0' => 'image/jpeg'
'MediaUrl0' => 'https://api.server.com/2010-04-01/Accounts/xxxxxxxx'
'MediaContentType1' => 'image/jpeg'
'MediaUrl1' => 'https://api.server.com/2010-04-01/Accounts/zzzzzzzz'

and so on, where the first parameters end with 0 and increment by 1 for every additional returned set of parameters.

What I would like to do is, based on the number of parameters indicated by the value of the NumMedia parameter, loop through each of these and set them into variables and then write out some database records. Something along the lines of:

if (isset($_POST['NumMedia']) && $_POST['NumMedia'] !== '') {
    $totalParams = $_POST['NumMedia'];
    $counter = 0;

    // set a variable for the first set of parameters
    $mediaContentType = $_POST['NumMediaXXX'] // XXX = $counter
    $mediaURL = $_POST['MediaUrlXXX'] // XXX = $counter

    // save these variables to database record
    // increment counter to get next set of parameters
    // exit when $counter = $totalParams

    $counter ++; 
}

I can conceptually see what I need to do just not sure how to get the loop going and to reference a dynamic POST parameter and exit the loop when I hit the number of expected parameters?

  • 写回答

1条回答 默认 最新

  • douyuan1049 2016-11-30 06:55
    关注

    You have to get the value through loops.

    if (isset($_POST['NumMedia']) && $_POST['NumMedia'] !== '') {
    
        $totalParams = $_POST['NumMedia'];
    
        for($i=0; $i<$totalParams; $i++)
        {
            // set a dynamic variables
            ${"mediaContentType" . $i}  = $_POST['mediaContentType'.$i]; // XXX = $counter
            ${"mediaURL" . $i} = $_POST['MediaUrl'.$i]; // XXX = $counter
        }
    
    }
    

    You have to set the value in dynamic variable and can access the value by $mediaContentType0 , $mediaURL0, $mediaContentType1 , $mediaURL1 and so on....

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)