Separate and join arrays [closed]

-3

I have the following array:

    Array
(
    [0] => Array
        (
            [setor_loja] => 43
            [impressao] =>  (P) Pizza 2 + Pizza 2\n
        )

)
Array
(
    [1] => Array
        (
            [setor_loja] => 83
            [impressao] => Acai 300 ml\n
        )

    [2] => Array
        (
            [setor_loja] => 83
            [impressao] => AA§ai 500 ml\n
        )

)
Array
(
    [3] => Array
        (
            [setor_loja] => 33
            [impressao] => Misto c/ ovo\n
        )

    [4] => Array
        (
            [setor_loja] => 33
            [impressao] => Misto duplo\n
        )

)

I would like the output to look like this: (P) Pizza 2 + Pizza 2 \ n (leave alone)

Acai 300 ml \ n + Acai 500 ml \ n (leaving together since these two products are from the same industry)

Mixed with egg \ n + Mixed double \ n (leave together since these two products are from the same industry)

    
asked by anonymous 21.07.2017 / 21:59

1 answer

3

I've assembled a combination that creates a new array with all products / group items by store code.

array_column() extract all ids from stores, array_flip() invert values with array keys returned by array_column() its output is something like:

Array
(
    [43] => 0
    [83] => 2
    [33] => 4
)

Then a check is made if the 'products' array exists if the store id exists, it copies the product description and plays into a new element.

$arr = array(
        array('setor_loja' => '43', 'impressao' => '(P) Pizza 2 + Pizza 2\n'),
        array('setor_loja' => '83', 'impressao' => 'Acai 300 ml\n'),
        array('setor_loja' => '83', 'impressao' => 'Açai 500 ml\n'),
        array('setor_loja' => '33', 'impressao' => 'Misto c/ ovo\n'),
        array('setor_loja' => '33', 'impressao' => 'Misto duplo\n')
);


$setores = array_flip(array_column($arr, 'setor_loja'));
$novo = array();
foreach($arr as $item){
    if(isset($setores[$item['setor_loja']])){
        $novo[$item['setor_loja']][] = $item['impressao'];
    }
}

The output of $novo is:

Array
(
    [43] => Array
        (
            [0] => (P) Pizza 2 + Pizza 2\n
        )

    [83] => Array
        (
            [0] => Acai 300 ml\n
            [1] => Açai 500 ml\n
        )

    [33] => Array
        (
            [0] => Misto c/ ovo\n
            [1] => Misto duplo\n
        )

)

To display the products in a store you can use the implode() function:

echo 'Loja 33 '. implode(' | ', $novo[33]);

Output:

Loja 33 Misto c/ ovo\n | Misto duplo\n
    
21.07.2017 / 22:26