-2

There is an array with the following format. I have used array_chunk function to format like the following array.

Array (
[0] => Array
    (
        [0] => Array
            (
                [SGST (2.5%)] => 2.5000
            )

        [1] => Array
            (
                [CGST (2.5%)] => 2.5000
            )

    )

[1] => Array
    (
        [0] => Array
            (
                [CGST (6%)] => 6.0000
            )

        [1] => Array
            (
                [SGST (6%)] => 6.0000
            )

    )
)

All I need my array to be displayed in the following format

Array
(
[0] => Array
    (
        [SGST (2.5%)] => 2.5000
        [CGST (2.5%)] => 2.5000

    )

[1] => Array
    (
       [CGST (6%)] => 6.0000
       [SGST (6%)] => 6.0000

    )
)

Help to create such format.Thanks

AAT
  • 411
  • 7
  • 16
Sonu Singh Jadoun
  • 245
  • 1
  • 3
  • 17

1 Answers1

0

try combination of array_map, array_reduce with array_merge

To know more about used function check function doc on php.net

<?php
$array = array (
    '0' => array
    (
        '0' => array
        (
            'SGST (2.5%)' => '2.5000'
        ),

        '1' => array
        (
            'CGST (2.5%)' => '2.5000'
        )

    ),

    '1' => array
    (
        '0' => array
        (
            'CGST (6%)' => '6.0000'
        ),

        '1' => array
        (
            'SGST (6%)' => '6.0000'
        )

    )
);

echo '<pre>';
$processed = array_map(function($a) {  return array_reduce($a, 'array_merge', array()); }, $array);
print_r($processed);

Output

Array
(
    [0] => Array
        (
            [SGST (2.5%)] => 2.5000
            [CGST (2.5%)] => 2.5000
        )

    [1] => Array
        (
            [CGST (6%)] => 6.0000
            [SGST (6%)] => 6.0000
        )

)
Chetan Ameta
  • 7,696
  • 3
  • 29
  • 44
  • array_map is too slow. Just use foreach with push ;) See: https://stackoverflow.com/questions/18144782/performance-of-foreach-array-map-with-lambda-and-array-map-with-static-function – yfain Aug 08 '17 at 07:59
  • why down vote? I posted the answer for the question. And I strongly believe there is no constraints for performance mentioned in question. is so? – Chetan Ameta Aug 08 '17 at 08:03