PHP / WP - iterate through multidimensional POST parameters

时间:2017-10-12 09:48:28

标签: php wordpress post

What is the proper way to iterate through multidimensional Array of POST parameters ? Example from Chrome Form Data Console below:

order[0][priority][]:1
order[0][priority][]:4
order[0][priority][]:2
order[0][priority][]:3
order[0][serviceId][]:28
order[0][serviceId][]:31
order[0][serviceId][]:29
order[0][serviceId][]:30
categoryId:5

I want to Update database table inside loop using above POST parameters.

$wpdb->query("
   UPDATE $table SET order=$priority
   WHERE category_id=$categoryId 
   AND service_id=$serviceId
");

First occurence of order[priority] is compact with first occurence of order[serviceId].

The question is how to create foreach to run UPDATE query? Thanks !

1 个答案:

答案 0 :(得分:1)

As described in your example I think you can iterate both arrays as the same time. If "priority" and "servicesId" have the same size you can do this:

$order = $_POST['order'];
$categoryId = $_POST['categoryId'];
$size = count($order[0]["priority"]);

foreach ($i=0; $i<$size; $i++) {
    $priority = $order[0]["priority"][$i];
    $serviceId = $order[0]["serviceId"][$i];

    $wpdb->query("
       UPDATE $table SET order=$priority
       WHERE category_id=$categoryId 
       AND service_id=$serviceId
    ");
}

Hope it helps!