RCP RCP - 1 month ago 4
JSON Question

creating json format in php for autocomplete search

i want to create json format in label and category.
and i am not getting the code of the JSON format in PHP
how to do this

$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

foreach ($arr as $key => $value) {

$data = 'label:'. $key.','.'category:'.$value;
}
echo json_encode($data);


I want to something like :
"[{label:"a", category:"1"},{label:"b", category:"2"},{label:"c", category:"3"}]


jQuery.ui.autocomplete not work ::

var test_url = Drupal.settings.url + '/all_list';

jQuery(".class").catcomplete({
delay: 500,
minLength: 3,
// source:data
source: function(request, response) {
$.ajax({
dataType: "json",
type : 'Get',
url: test_url,
success: function(data) { console.log(data);}

});
}

});


i have getting via console.log(data);

[{"label":"a","category":1},{"label":"b","category":2}, {"label":"c","category":3},{"label":"d","category":4},{"label":"e","category":5}]

Answer

Simply like this

<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
$final = array();
foreach($arr as $key=>$value){
  $final[]=["label"=> $key,"category" => $value];
}
echo json_encode($final);
?>

output is :

[{"label":"a","category":1},{"label":"b","category":2},{"label":"c","category":3},{"label":"d","category":4},{"label":"e","category":5}]

Live demo : https://eval.in/663626