Count Similar Array Keys

前端 未结 4 1588
花落未央
花落未央 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 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

     '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); 
    

提交回复
热议问题