我有一个包含一些整数的 php 数组,如下所示
Array
(
[0] => 41
[1] => 64
[2] => 51
[3] => 42
[4] => 65
[5] => 52
[6] => 66
[7] => 67
)
Run Code Online (Sandbox Code Playgroud)
现在我想像这样创建对象的json数组。
[{"assosiated_id": 41}, {"assosiated_id": 42}, {"assosiated_id": 51}, {"assosiated_id": 52}, {"assosiated_id": 64}, {"assosiated_id": 65}, {"assosiated_id": 66}, {"assosiated_id": 67}]
Run Code Online (Sandbox Code Playgroud)
我曾尝试将此数组转换为关联数组,然后编码为 json 但关联数组不能有重复值。请告诉这是最好的方法吗?
$a = [41, 64, 51, 42, 65, 52, 66, 67];
sort($a);
$b = [];
foreach ($a as $v) {
$b[] = ['associated_id' => $v];
}
echo json_encode($b);
Run Code Online (Sandbox Code Playgroud)
给
[{"associated_id":41},{"associated_id":64},{"associated_id":51}, {"associated_id":42},{"associated_id":65},{"associated_id":52},{"associated_id":66},{"associated_id":67}]
Run Code Online (Sandbox Code Playgroud)
或者,您可以在评论中使用Mark Baker 的 oneliner
如果您使用的是旧版本的 PHP,您可能必须像这样编写代码
$a = array(41, 64, 51, 42, 65, 52, 66, 67);
sort($a);
$b = array();
foreach ($a as $v) {
$b[] = array('associated_id' => $v);
}
echo json_encode($b);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
768 次 |
| 最近记录: |