0

I want to send an array table from PHP to JSON. my array table is simple:

[0] => 10

[1] => 20

I want to see it in Json as

{ "values":["10","20"] }

In PHP, I tried

  $values=array("10","20");
  echo(
         '{
            "values": '.$values.',
            "text": "abcdef"
         }'
  );

But it displays: { "values":Array] }

Do you know how I can do this ? (Values in my arrays are not always with a size of 2, it can evolve depending, so I don't want to use values[0] and values[1].

2
  • you really don't need to write json string by hand you know, there's json_encode for that Commented Apr 30, 2019 at 9:15
  • Create an array, and encode it using json_encode. There are plenty of examples here and on the php main site. Commented Apr 30, 2019 at 9:15

1 Answer 1

1

json_encode - Returns the JSON representation of a value

$arr = [10,20];
$newArray = [
     'values' => $arr,
     'text'   => 'abcd'
];
echo $json = json_encode($newArray);
Sign up to request clarification or add additional context in comments.

4 Comments

Just echo the json_encode function directly there's no need to initiate a new variable
What is the advantage of that?
Where are you going to use the $json variable? nothing right?
This is for the explanation purpose only, it's on OP to use direct or with variable, may be in the middle of the code he needs same value

Your Answer

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.