Group arrays with same Id

Asked

Viewed 229 times

-1

I’m doing a foreach, where I group the values by id, and I find myself with the following problem: My foreach is currently so

foreach ($skuProduto as $skuProduto ) { 

            foreach ($skuProduto->variacao as $variacao ) { 

                $variacoes[] = [

                     "name" => $variacao ->valor, 
                     "value" => $variacao ->item
                 ];

            $data[] = [             
            "Id"=>  $variacao->id,
            "Attributes"=> [ 
                 [
                    $variacoes,

                 ]

                ]
            ];

          }

        }

and returns the value to me in the following manner

[
    {
        "Id": "001",
        "Attributes": [
            {
                "name": "Preto",
                "value": "Cor"
            }
        ]
    },
    {
        "Id": "002",
        "Attributes": [
            {
                "name": "Preto",
                "value": "Cor"
            }
        ]
    },
    {
        "Id": "001",
        "Attributes": [
            {
                "name": "tamanho",
                "value": "10"
            }
        ]
    },
    {
        "Id": "002",
        "Attributes": [
            {
                "name": "tamanho",
                "value": "5"
            }
        ]
    },

And I need it to come back by grouping the values according to the id in this way

[
    {
        "Id": "001",
        "Attributes": [
            {
                "name": "Preto",
                "value": "Cor"
            },
            {
                "name": "tamanho",
                "value": "10"
            }
        ]
    },
    {
        "Id": "002",
        "Attributes": [
            {
                "name": "Preto",
                "value": "Cor"
            },
            {
                "name": "tamanho",
                "value": "5"
            }
        ]
    }
]

what is the correct way to do the foreach so that the values return correctly

1 answer

0


Try it this way:

$arraySku = array();
$indice = 0;
foreach ($skuProduto as $skuProduto ) { 
  foreach ($skuProduto as $key => $variacao){
    $arraySku[$indice]['id] = $key;
    $variacoes[] = [
        "name" => $variacao ->valor, 
        "value" => $variacao ->item
    ];
    $arraySku[$indice]['Attributes'] = $variacoes;
    $indice++;
  }
}

$encodedSku = json_encode($arraySku);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.