如何在php中从php数组创建json对象数组?

时间:2015-06-19 11:49:56

标签: php arrays json

我有一个包含一些整数的php数组,如下所示

Array
(
    [0] => 41
    [1] => 64
    [2] => 51
    [3] => 42
    [4] => 65
    [5] => 52
    [6] => 66
    [7] => 67
)

现在我想创建像这样的对象的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}]

我尝试将此数组转换为assosiative数组然后编码为json但是assosiative数组不能有重复值。请告诉哪个是最好的方法呢?

3 个答案:

答案 0 :(得分:4)

$a = [41, 64, 51, 42, 65, 52, 66, 67];
sort($a);
$b = [];
foreach ($a as $v) { 
    $b[] = ['associated_id' => $v]; 
}
echo json_encode($b);

给出

[{"associated_id":41},{"associated_id":64},{"associated_id":51}, {"associated_id":42},{"associated_id":65},{"associated_id":52},{"associated_id":66},{"associated_id":67}]

或者,您可以在评论中使用Mark Baker's 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);

答案 1 :(得分:1)

请将您的数组相应地更改为php语法,如果这是您的意思

https://eval.in/384328

<?php
$data = Array
(
    0 => 41,
    1 => 64,
    2 => 51,
    3 => 42,
    4 => 65,
    5 => 52,
    6 => 66,
    7 => 67
);

$mapFunc = function($n) {
  return array('assosiated_id' => $n);
};

echo json_encode(array_map($mapFunc, $data));

答案 2 :(得分:0)

检查

<?php
$array = array(41,52,64,67,68,89,34);

$new = [];
foreach($array as $a)
{
    $b = array('assosiated_id' => $a);
    $new[] =$b;
}

echo json_encode($new);

输出

[
{
assosiated_id: 41
},
{
assosiated_id: 52
},
{
assosiated_id: 64
},
{
assosiated_id: 67
},
{
assosiated_id: 68
},
{
assosiated_id: 89
},
{
assosiated_id: 34
}
]