是否要将JSON格式的数组转换为特定格式?

时间:2019-07-11 04:54:39

标签: php laravel

我有一个格式为

的数组
Array
(
[1] => Array
    (
        [Id] => 1
        [Name] => Anaa Airport (AAA)
        [IsDomestic] => 0
    )

[2] => Array
    (
        [Id] => 2
        [Name] => Arrabury Airport (AAB)
        [IsDomestic] => 0
    )
)

我想将其更改为此格式

[
{"Name":"Anaa (AAA)","Id":1,"IsDomestic":0},
{"Name":"Arrabury (AAB)","Id":2,"IsDomestic":0},
]

我已经尝试过json_encode函数,但这给了我类似的东西

{"1":{"Id":1,"Name":"Anaa Airport (AAA)","IsDomestic":0},
 "2":{"Id":2,"Name":"Arrabury Airport (AAB)","IsDomestic":0}
}

我不想要那个1,2键。

我想获取提到的确切形式的数据。

3 个答案:

答案 0 :(得分:0)

与使用array_map中的array_values进行输出相比,您可以使用json_encode以所需的顺序重新排列数组

$r = array_map(function($v){
  return [
      'Name' => str_replace('Airport ','',$v['Name']), 
      'Id' => $v['Id'], 
      'IsDomestic' => $v['IsDomestic']
  ];
}, $a1);//$a1 is the input array
echo json_encode(array_values($r));

工作示例:https://3v4l.org/GZr6Q

答案 1 :(得分:-1)

使用array_values()删除索引

$json_out = json_encode(array_values($your_array_here));

答案 2 :(得分:-1)

$your_array = Array
(
[1] => Array
    (
        [Id] => 1
        [Name] => Anaa Airport (AAA)
        [IsDomestic] => 0
    )

[2] => Array
    (
        [Id] => 2
        [Name] => Arrabury Airport (AAB)
        [IsDomestic] => 0
    )
);

$new_array = [];
foreach($your_array as $array)
{
  $new_array[] = json_encode($array);
}

dd($new_array);