Reputation: 3986
I have a table users. in this table i have a field and in that field data is something like this test,test1,test2. I am using ajax to fetch the data from this table and show it on php file.
I am able to fetch the data but due to select2 plugin. i need to make proper formatting of this data.
fetch.php
$data = array();
while ($result->fetch()) {
$data['title'] = $title;
$data['opening'] = $opening;
$data['description'] = $description;
$data['keywords'] = $keywords;
}
echo json_encode($data);
keywords field have data something like this test,test1,test2
i need to make it in proper json format like this.
id:test text:test
id:test1 text:test1
so on.
Is it possible to make it like.
Upvotes: 1
Views: 487
Reputation: 72269
Add this code in your code (new code have comment):-
<?php
$data = array();
while ($result->fetch()) {
$data['title'] = $title;
$data['opening'] = $opening;
$data['description'] = $description;
$data['keywords'] = $keywords;
}
// code need to add
$new_data = explode(',',$data['keywords']);
$final_data = array();
foreach($new_data as $new_dat){
$final_data[] = array('id'=>$new_dat,'text'=>$new_dat);
}
echo "<pre/>";print_r( $final_data);
$data['keywords'] = $final_data; // assingnment
// print json encoded data in last
echo json_encode($data);
?>
An example code:- https://eval.in/528365
Upvotes: 1
Reputation: 2553
Is this what are you looking for:
while ($result->fetch()) {
$data['title'] = $title;
$data['opening'] = $opening;
$data['description'] = $description;
$data['keywords'] = $keywords;
$data = array(
"id" => $data['keywords'],
"text" => $data['keywords']
);
}
echo json_encode($data);
Upvotes: 1
Reputation: 2469
Yes you can make and two dimensional array inside empty array and $arrays = ('a' => 'b') like this then json_encode($arrays) now you get json object
Upvotes: 1