Search code examples
phparraysmultidimensional-arraygroupingprefix

Remove prefix from keys of an associative array and use the prefix as the first level key of a grouped 2d array


I have array from POST like this:

  '0,id_product' =>  '217' 
  '0,checked' =>  '217'
  '0,price_setup_original' =>  '1.00' 
  '1,price_setup_original' =>  '7.00' 
  '1,price_setup_res' =>  '7.00' 
  '1,price_monthly_original' => '50.00' 
  '2,price_setup_res' => '0.00' 
  '2,price_monthly_original' =>  '40.00' 
  '2,price_monthly_res' =>  '40.00'

i want to iterate it like this example, need help!

array = (
0 -> array(
      'id_product' =>  '217',
      'checked' =>  '217',
      'price_setup_original' =>  '1.00' 
     ),
1 -> array(
      'id_product' =>  '217',
      'checked' =>  '217',
      'price_setup_original' =>  '1.00' 
     ),
);

Solution

  • Try:

    $formatted = array();
    
    $post = array(
      '0,id_product' =>  '217', 
      '0,checked' =>  '217',
      '0,price_setup_original' =>  '1.00', 
      '1,price_setup_original' =>  '7.00',
      '1,price_setup_res' =>  '7.00', 
      '1,price_monthly_original' => '50.00', 
      '2,price_setup_res' => '0.00', 
      '2,price_monthly_original' =>  '40.00', 
      '2,price_monthly_res' =>  '40.00'
    );
    
    foreach($post as $keys => $val){
        list($key1, $key2) = explode(",", $keys);
        $formatted[$key1][$key2] = $val;
    }
    
    var_dump($formatted);
    

    Codepad example.