merge将对象数组合并为具有唯一对象的数组

问题描述 投票:3回答:2

我有一个各种对象的数组,但我需要将这些对象转换为唯一的对象。下面我分享我的代码。

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

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

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

答案

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

但我需要将这些对象转换为一个,就像这样

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

有人可以帮帮我吗?

php arrays laravel
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

0
投票

编辑:@Tpojka的答案肯定看起来更合适。仅当您无法更改最初检索数据的方式时才使用以下方法(我对Laravel不够熟悉)。

以下应该有效:

// 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);
© www.soinside.com 2019 - 2024. All rights reserved.