I have an arrays like follows:
Array
(
[option] => nos
[optioncost] => 10
)
Array
(
[option] => opts
[optioncost] => 20
)
Array
(
[option] => opts
[optioncost] => 30
)
need to convert this as like the following json format
[{"option":nos,"optioncost":10},{"option":opts,"optioncost":20},{"option":optse,"optioncost":30}]
Barmar
789k57 gold badges555 silver badges669 bronze badges
2 Answers 2
Try this code :
<?php
$arr = array();
$arr[] = array('option' => 'nos',
'optioncost' => 10
);
$arr[] = array('option' => 'opts',
'optioncost' => 20
);
$arr[] = array('option' => 'optse',
'optioncost' => 30
);
echo json_encode($arr);
?>
Output :
[{"option":"nos","optioncost":10},{"option":"opts","optioncost":20},{"option":"opts","optioncost":30}]
Hope this helps !
answered Apr 21, 2018 at 13:09
Alan
3961 gold badge4 silver badges17 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Pedro Lobito
Why would the OP try your code? You should always provide an explanation whenever possible.
The json example you've provided isn't valid because strings aren't quoted (nos / opts), something you could have easily tested on any online json validator.
You'll need to construct proper arrays - where strings are "quoted" - and use the json_encode() function, i.e.:
$arr1 = ['option' => "nos", 'optioncost' => 10];
$arr2 = ['option' => "opts", 'optioncost' => 20];
$arr3 = ['option' => "opts", 'optioncost' => 30];
echo json_encode([$arr1, $arr2, $arr3]);
# [{"option":"nos","optioncost":10},{"option":"opts","optioncost":20},{"option":"opts","optioncost":30}]
Note:
Strings need to be quoted, but floats, ints or bools don't.
answered Apr 21, 2018 at 13:27
Pedro Lobito
99.8k36 gold badges274 silver badges278 bronze badges
Comments
default
$arr=[$arr1,$arr2,$arr3];.