0

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
asked Apr 21, 2018 at 12:58
3
  • you created different array. create single array and push data on different index. Commented Apr 21, 2018 at 13:00
  • thanks for the reply....i have six different input fileds how to make them as single array Commented Apr 21, 2018 at 13:02
  • If you have a fixed number of arrays, you can do $arr=[$arr1,$arr2,$arr3];. Commented Apr 21, 2018 at 13:07

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Why would the OP try your code? You should always provide an explanation whenever possible.
0

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}]

DEMO


Note:

Strings need to be quoted, but floats, ints or bools don't.

answered Apr 21, 2018 at 13:27

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.