简体   繁体   中英

how to create json array of objects from php array in php?

I am having a php array containing some integer numbers as below

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

Now i want to create json array of object like this.

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

I have tried converting this array into assosiative array then encode to json but assosiative array can not have duplicate values.please tell which is the best way to do it?

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

gives

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

Alternatively you can just use the Mark Baker's oneliner in your comments

If you are using an older version of PHP you may have to code it like this

$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);

please, change your array accordingly to php syntax, if this is what you meant

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));

Check this

<?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);

output will be

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM