I have an array in the format
Array
(
[1] => Array
(
[Id] => 1
[Name] => Anaa Airport (AAA)
[IsDomestic] => 0
)
[2] => Array
(
[Id] => 2
[Name] => Arrabury Airport (AAB)
[IsDomestic] => 0
)
)
I want to change it to this format
[
{"Name":"Anaa (AAA)","Id":1,"IsDomestic":0},
{"Name":"Arrabury (AAB)","Id":2,"IsDomestic":0},
]
I have tried json_encode function but this is giving me something like this
{"1":{"Id":1,"Name":"Anaa Airport (AAA)","IsDomestic":0},
"2":{"Id":2,"Name":"Arrabury Airport (AAB)","IsDomestic":0}
}
I don't want that 1,2 keys which.
I want to get the data in the exact form mentioned.
You can use array_map
to rearrange the array in the desired order, than use array_values
in json_encode
for the output
$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));
Working example : https://3v4l.org/GZr6Q
使用array_values()删除索引
$json_out = json_encode(array_values($your_array_here));
$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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.