Count Similar Array Keys

前端 未结 4 1587
花落未央
花落未央 2021-01-13 18:43

I have a POST request coming to one of my pages, here is a small segment:

[shipCountry] => United States
[status] => Accepted
[sku1] => test
[produc         


        
相关标签:
4条回答
  • 2021-01-13 18:51

    What Gumbo meant with his "use array instead" comment is the following:

    In your HTML-form use this:

    <input type="text" name="quantity[]" />
    

    and $_POST['quantity'] will then be an array of all containing all of your quantities.

    If you need to supply an id you can also do this:

    <input type="text" name="quantity[0]" />
    

    $_POST['quantity][0] will then hold the corresponding quantity.

    0 讨论(0)
  • 2021-01-13 19:04

    Though there be plenty of examples, if you're guaranteed that the numbers should be contiguous, I usually take the approach:

    <?php 
    $i = 1; 
    while( isset($_POST['product'.$i) )
    {
        // do something
        $i++;
    }
    
    0 讨论(0)
  • 2021-01-13 19:09

    Well, if you know that every product will have a corresponding array key matching "productN", you could do this:

    $productKeyCount = count(preg_grep("/^product(\d)+$/",array_keys($_POST)));
    

    preg_grep() works well on arrays for that kind of thing.

    0 讨论(0)
  • 2021-01-13 19:11

    As mentioned by gumbo you could group all parameters describing one item in its own array which usually makes it easier to iterate them. You may not have control over the POST parameters but you can restructure them like e.g. with

    <?php
    
    $testdata = array(
      'shipCountry' => 'United States',
      'status' => 'Accepted',
      'sku1' => 'test1',
      'product1' => 'Test Product1',
      'quantity1' => '1',
      'price1' => '0.01',
      'sku2' => 'test2',
      'product2' => 'Test Product2',
      'quantity2' => '2',
      'price2' => '0.02'
    );
    
    $pattern = '/^(.*\D)(\d+)$/';
    $foo = array('items'=>array());
    foreach($testdata as $k=>$v) {
      if ( preg_match($pattern, $k, $m) ) {
        $foo['items'][$m[2]][$m[1]] = $v;
      }
      else {
        $foo[$k] = $v;
      }
    }
    print_r($foo); 
    
    0 讨论(0)
提交回复
热议问题