Algorithm of converting the mass into another format



  • Please help me out of mass:

               Array
                    (
                        [2] => Array
                            (
                                [param1] => 2
                                [param2] => Значение2
                            )
    
                    [3] => Array
                        (
                            [param1] => 3
                            [param3] => Значение3
                        )
    
                    [5] => Array
                        (
                            [param1] => 2
                            [param4] => Значение4
                        )
    
                    [6] => Array
                        (
                            [param1] => 3
                            [param5] => Значение5
                        )
    
                )
    

    Get this:

               Array
    (
    [1] => Array
    (
    [param1] => 2
    [param2] => Значение2
    [param4] => Значение4
    )

                    [2] => Array
                        (
                            [param1] => 3
                            [param3] => Значение3
                            [param5] => Значение5
                        )
                )
    

    The names of keys are always numerical and not orderly, but they always grow.

    There's always a couple (and only a couple) with the same meaning. param1

    Number of couples not limited



  • Just go through the mass and complete the structure.

    public function extractStructure(array $source) {
        $structure = [];
        foreach ($source as $values) {
            $id = $values['param1'];
            if (!isset($structure[$id])) {
                $structure[$id] = [];
            }
            foreach ($values as $key => $value) {
                $structure[$id][$key] = $value;
            }
        }
        return $structure;
    }
    



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2