Reputation: 157
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
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
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