0

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'},...],
2
  • You will have to convert the indexed list into subarrays each, if you want to split it into id: and text:. And the shallow answers are incorrect when it comes to the output syntax (unquoted keys), but presumably so are you. Commented Mar 20, 2013 at 11:07
  • when i do json_encode i get {"1":"Laravel","2":"Volta","3":"Web","4":"Design","5":"Development"}but i need {id: 1, text: 'Laravel'},{id: 2, text: 'Volta'},{id: 3, text: 'Web'} Commented Mar 20, 2013 at 11:08

4 Answers 4

4

use json_encode

echo json_encode($array);
Sign up to request clarification or add additional context in comments.

2 Comments

This won't produce what is required
@RMcLeod that's why i commented to see baba's answer.
3

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

1 Comment

almost there thank you but is there a way to only get [{"id":1,"text":"Laravel"},{"id":2,"text":"Volta"},{"id":3,"text":"Web"},{"id":4,"text":"Design"},{"id":5,"text":"Development"}]
1

Just use php's function json_encode

1 Comment

This doesn't provide the required output
1

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

Comments

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.