在laravel中将数组键转换为对象

时间:2019-07-04 10:20:06

标签: php laravel

我有一个数组作为flight_names:

           [
               "Spice Jet",
               "Go Air",
               "Air India",
               "Vistara"
           ]

我希望它更改为结构

           [
               {"flight_name":"Spice Jet"},
               {"flight_name":"Go Air"},
               {"flight_name":"Air India"},
               {"flight_name":"Vistara"}
           ]

任何人都可以帮助我,如何在LARAVEL或PHP中更改为这种格式。

2 个答案:

答案 0 :(得分:1)

如果json_encode是json输出,则可以使用

$arr    = ["Spice Jet", "Go Air", "Air India", "Vistara"];
$result = json_encode(array_map(function ($item) {
    return (array_combine(['flight_name'], [$item]));
}, $arr), JSON_PRETTY_PRINT);
print_r($result);die;

参考array-combinearray-mapjson-encode

  

JSON_PRETTY_PRINT
  在返回的数据中使用空格对其进行格式化。自PHP 5.4.0起可用。

Demo

简单的foreach循环

$arr = ["Spice Jet", "Go Air", "Air India", "Vistara"];
foreach($arr as &$v){
    $v = (array_fill_keys([$v], "flight_name"));
}
print_r(json_encode($arr));die;

参考array-fill-keys

Demo

array_map的简化版本,

$result =array_map(function($item){
    return ['flight_name' => $item];
}, $arr);

Demo

简化的foreach,

foreach($arr as &$v){
    $v = ['flight_name' => $v];
}
print_r(json_encode($arr));die;

Demo

要反转输出,

foreach($arr as &$v){
    $v = array_flip(json_decode($v, true));
}

输出

[
    {
        "flight_name": "Spice Jet"
    },
    {
        "flight_name": "Go Air"
    },
    {
        "flight_name": "Air India"
    },
    {
        "flight_name": "Vistara"
    }
]

答案 1 :(得分:-1)

 $airlineArray=["Spice Jet", "Go Air", "Air India", "Vistara"];
    $finalArray=[];
    foreach($airlineArray as $key=>$value)
     {
       $arrayValue = ['flight_name' => $value];
          $finalArray[]=$arrayValue;
      }
     return $finalArray;