【问题标题】:merge Array of objects into array with unique object将对象数组合并为具有唯一对象的数组
【发布时间】:2018-08-10 03:25:50
【问题描述】:

我有一个包含各种对象的数组,但我需要将这些对象变成唯一的对象。下面我分享我的代码。

$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


    【解决方案1】:

    编辑: @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);
    

    【讨论】:

      【解决方案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
      

      【讨论】:

      • 谢谢。请记住,在 Laravel 中,您必须要么写$o = new \stdClass(),要么在文件顶部添加 use 语句。
      • @PaulinhoRodrigues 刚刚在这里签入了一些代码。你说得对,我的意思是我在那里使用了反斜杠。编辑。
      猜你喜欢
      • 2023-03-21
      • 1970-01-01
      • 2017-02-21
      • 1970-01-01
      • 2022-01-01
      • 2022-12-06
      • 2022-11-17
      • 2021-11-12
      • 1970-01-01
      相关资源
      最近更新 更多