3

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?

2 Answers 2

2
$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
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. Just to remember, in Laravel you must either write$o = new \stdClass() or add a use statement on the top of the file.
@PaulinhoRodrigues Just checked in some code here. You are quite right, I mean I used backslash there. Editing.
0

Edit: @Tpojka's answer definitely looks more appropriate. Use the following one only if you can't change the way you retrieve data initially (I'm not familiar enough with Laravel).

The following should work:

// Take your initial JSON
$input = <<<JSON
[
  { "INICIAL": "Inicial"},{ "RELATORIOS": "Relatórios"},{ "FUNCIONARIO": "Funcionário"},{ "DATA": "Data"},{ "ANEXAR_IMAGEM": "Anexar imagem"},{ "DISCIPLINA": "Disciplina"}
]
JSON;

// Transform it into a PHP array
$input_as_array = json_decode($input);

// Reduce it into an associative array
$associative_array = array_reduce($input_as_array, function($associative_array, $item) {
    return $associative_array += (array)$item;
}, []);

// Encode it back into JSON, as an array
$result = json_encode([$associative_array], JSON_PRETTY_PRINT);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.