user1994529
user1994529

Reputation: 157

Converting a PHP array to JSON string

I have an array that looks like this:

Array ( 
       [1] => Laravel 
       [2] => Volta 
       [3] => Web 
       [4] => Design 
       [5] => Development 
      )

Now I want to convert this array to a string that has to look like this

data: [{id: 1, text: 'Laravel'},{id: 2, text: 'Volta'},{id: 3, text: 'Web'},...],

Upvotes: 0

Views: 158

Answers (4)

Baba
Baba

Reputation: 95161

YOu can try

$data = Array(
        1 => "Laravel",
        2 => "Volta",
        3 => "Web",
        4 => "Design",
        5 => "Development"
);

array_walk($data, function (&$item, $key) {
    $item = array("id"=>$key,"text"=>$item);
});

print(json_encode(array("data"=>array_values($data))));

Output

{"data":[{"id":1,"text":"Laravel"},{"id":2,"text":"Volta"},{"id":3,"text":"Web"},{"id":4,"text":"Design"},{"id":5,"text":"Development"}]}

Upvotes: 3

Jorge Y. C. Rodriguez
Jorge Y. C. Rodriguez

Reputation: 3449

you can do that with json_encode and with that you will be able to parset with javascript to show it to users

Upvotes: 1

Yogesh Suthar
Yogesh Suthar

Reputation: 30488

use json_encode

echo json_encode($array);

Upvotes: 4

Ven
Ven

Reputation: 19040

Just use php's function json_encode

Upvotes: 1

Related Questions