Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

merge Array of objects into array with unique object

I have a array of various object, but I need turn this objects into unique object. Below I share my code.

$result = [];
$idiomas = Idioma::all()->toArray();

foreach ($idiomas as $lang) {
    $result[] =  [
      $lang['palavra_chave'] => $lang[$id]
    ];
}

return response()->json($result);

reponse

[
  { "INICIAL": "Inicial"},{ "RELATORIOS": "Relatórios"},{ "FUNCIONARIO": "Funcionário"},{ "DATA": "Data"},{ "ANEXAR_IMAGEM": "Anexar imagem"},{ "DISCIPLINA": "Disciplina"}
]

But I need transform this objects into one, like this

[
    {
        "INICIAL": "Inicial",
        "RELATORIOS": "Relatórios",
        "FUNCIONARIO": "Funcionário",
        "DATA": "Data",
        "ANEXAR_IMAGEM": "Anexar imagem",
        "DISCIPLINA": "Disciplina"
    }
]

anyone can help me?

like image 253
Paulinho Rodrigues Avatar asked Aug 29 '26 07:08

Paulinho Rodrigues


1 Answers

$idiomas = Idioma::all()->toArray();

if (count($idiomas)) {
    //$result = new stdClass; # wouldn't work without base namespace
    $result = new \stdClass;
    foreach ($idiomas as $lang) {
        $result->{$lang['palavra_chave']} = $lang[$id];
    }
    return response()->json([$result]);
}

// otherwise
like image 142
Tpojka Avatar answered Aug 31 '26 22:08

Tpojka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!