I have around 700 product list in my Databse table.
I am using bootstrap's tokenfield for auotcomplete, i have to use auto complete in search textbox.
I am getting syntax error :
SyntaxError: missing ] after element list
...B','Lino Perros Men's Leather Wallet - Pink','Lenovo A269i','Lenovo S660 - Tita**
in console.
<?php $t = $this->general_model->auto_complete_sug(); ?>
$( document ).ready(function() {
$('#tokenfield-2').tokenfield({
autocomplete: {
source: <?=$t?>,
delay : 100
},
limit: 1,
minLength: 1,
showAutocompleteOnFocus: true
});
});
<input type="text" class="span2" name="search" id="tokenfield-2" placeholder="Search...">
In my model: I have created this functions:
public function auto_complete_sug()
{
$data = $this->auto_complete_token_fun();
$data1 = explode(',', $data);
$data1 = array_unique($data1);
foreach ($data1 as $value1) {
$temparr[] = $value1;
}
$str = '[';
$c = count($temparr);
$counter = 0;
foreach ($temparr as $val) {
$counter++;
$str .= "'".$val."'";
if($counter < $c){
$str .= ",";
}
}
$str .= ']';
return $str;
}
public function auto_complete_token_fun()
{
// $this->db->query("SET GLOBAL group_concat_max_len = 10000000");
$q = $this->db->query("SELECT GROUP_CONCAT( sub_category_name ) AS scname
FROM `tbl_subcategory` WHERE status = 'Active' ");
if($q->num_rows() > 0)
{
$d = $q->row_array();
return $d['scname'];
}
else
{
return '';
}
}
Please help!!
Related
I am doing a project with Laravel 7. I have to read a csv file and through a controller passing the data in json format to a view.
Unfortunately I don't know how to do that.
These are my controller methods:
public function index($source)
{
$source = strtolower($source);
switch ($source) {
case "csv":
$file_csv = base_path('transactions.csv');
$transactions = $this->csvToJson($file_csv);
dd(gettype($transactions));
return view('transactions', ['source' => $source, 'transactions' => $transactions]);
break;
case "db":
$transactions = Transaction::all();
dd(gettype($transactions));
return view('transactions', ['source' => $source, 'transactions' => $transactions]);
break;
default:
abort(400, 'Bad sintax error.');
}
}
function csvToJson($filename = '', $delimiter = ',')
{
if (!file_exists($filename) || !is_readable($filename)) {
return false;
}
$header = null;
$data = array();
if (($handle = fopen($filename, 'r')) !== false)
{
while (($row = fgetcsv($handle, 1000, $delimiter)) !== false)
{
if (!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
As you can see, under the two cases I put a dd with a gettype function inside. In the first case I receive uncorrectly the response array, in the second one I receive correctly the response object.
The converted csv file should have this format:
[{"id":1,"code":"T_218_ljydmgebx","amount":"8617.19","user_id":375,"created_at":"2020-01-19T16:08:59.000000Z","updated_at":"2020-01-19T16:08:59.000000Z"},
{"id":2,"code":"T_335_wmhrbjxld","amount":"6502.72","user_id":1847,"created_at":"2020-01-19T16:08:59.000000Z","updated_at":"2020-01-19T16:08:59.000000Z"}]
Do you know how to convert the array transactions into a json object in the first case?
I don't know if there is any build-in solution on Laravel, but it can be done by PHP.
I didn't test my code. So it might not work, or contain some typos, but I'm sure it will give you some directions.
$cols = ["id","code","amount","user_id","created_at","updated_at"];
$csv = file('folder/name.csv');
$output = [];
foreach ($csv as $line_index => $line) {
if ($line_index > 0) { // I assume the the first line contains the column names.
$newLine = [];
$values = explode(',', $line);
foreach ($values as $col_index => $value) {
$newLine[$cols[$col_index]] = $value;
}
$output[] = $newLine;
}
}
$json_output = json_encode($output);
You can just do this :
$csv= file_get_contents($file);
$array = array_map('str_getcsv', explode(PHP_EOL, $csv));
$json json_encode($array);
If you want to return json object
return $json;
If you want to create a .json file
// Pure PHP
$file = fopen('results.json', 'w');
fwrite($file, $json);
fclose($file);
// Laravel using Storage
Storage::disk('local')->put('public/result.json', $json);
I hope this helps somone.
I have an email marketing application where I made bulk importers. So here is their CSV TO JSON code.
function convert_csv_to_json($csv_data){
// CSV to JSON process 1
$context = array(
'http'=>array(
'follow_location' => false,
'max_redirects' => 1000000
)
);
$context = stream_context_create($context);
if (($handle = fopen($csv_data, "r", false, $context)) !== FALSE) {
$csvs = [];
while(! feof($handle)) {
$csvs[] = fgetcsv($handle);
}
$datas = [];
$column_names = [];
foreach ($csvs[0] as $single_csv) {
$column_names[] = $single_csv;
}
foreach ($csvs as $key => $csv) {
if ($key === 0) {
continue;
}
foreach ($column_names as $column_key => $column_name) {
$datas[$key-1][$column_name] = $csv[$column_key];
}
}
return $json = json_encode($datas);
}
// OR
// CSV to JSON process 1
$cols = ['id',
'owner_id',
'name',
'email',
'country_code',
'phone',
'favourites',
'blocked',
'trashed',
'is_subscribed',
'deleted_at',
'created_at',
'updated_at.'];
$csv = file($csv_data);
$output = [];
foreach ($csv as $line_index => $line) {
if ($line_index > 0) { // I assume the the first line contains the column names.
$newLine = [];
$values = explode(',', $line);
foreach ($values as $col_index => $value) {
$newLine[$cols[$col_index]] = $value;
}
$output[] = $newLine;
}
}
return $json_output = json_encode($output);
}
<?php function getCurrencyFor($arr, $findCountry) {
foreach($arr as $country) {
if ($country->name->common == $findCountry) {
$currency = $country->currency[0];
$capital = $country->capital;
$region = $country->region;
break;
}
}
return $country();
}
$json = file_get_contents("https://raw.githubusercontent.com/mledoze/countries/master/countries.json");
$arr = json_decode($json);
// Call our function to extract the currency for Angola:
$currency = getCurrencyFor($arr, "Aruba");
echo $country('$capital');
echo $country('$currency');
echo $country('$region');
?>
I followed this post - https://stackoverflow.com/a/38906191/3939981
If I rewrite the code inside function, it works
<?php function getCurrencyFor($arr, $findCountry) {
foreach($arr as $country) {
if ($country->name->common == $findCountry) {
$currency = $country->currency[0];
$capital = $country->capital;
$region = $country->region;
echo $capital;
echo $currency;
echo $region;
break;
}
}
return $currency;
}
$json = file_get_contents("https://raw.githubusercontent.com/mledoze/countries/master/countries.json");
$arr = json_decode($json);
// Call our function to extract the currency for Angola:
$currency = getCurrencyFor($arr, "Aruba");
?>
Maybe some parts of the code did not work..Any comments and thoughs
You could use this code. Note that if you want a function to return three values, you should create an array with those values, and return that array. I also renamed the function, since it does not only return currency information:
function getCountryInfo($arr, $findCountry) {
foreach($arr as $country) {
if ($country->name->common == $findCountry) {
return array(
"currency" => $country->currency[0],
"capital" => $country->capital,
"region" => $country->region
);
}
}
}
$json = file_get_contents("https://raw.githubusercontent.com/mledoze/countries/master/countries.json");
$arr = json_decode($json);
// Call our function to extract the currency for Angola:
$country = getCountryInfo($arr, "Aruba");
echo $country['capital'] . "<br>";
echo $country['currency'] . "<br>";
echo $country['region'] . "<br>";
if ($tag == 'get_rajkot')
{
$data=$db->get_rajkot();
if($data!=false)
{
$valueresult=array();
foreach ($data as $value)
{
$valueresult=$value;
echo json_encode($valueresult);
}
}
else
{
// failed to store
$response["error"] = 1;
$response["error_msg"] = "Error occured..No get_headlines image found...";
echo json_encode($response);
}
}
db_function.php
public function get_rajkot()
{
$result = mysql_query("SELECT * FROM wp_term_relationships join wp_posts where ID=`object_id` and term_taxonomy_id=19 ORDER BY object_id DESC LIMIT 10") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0)
{
$rows = array();
while($r = mysql_fetch_assoc($result))
{
$rows[] = $r;
//print_r($rows);
}
return $rows;
}
else
{
// profile not found
return false;
}
}
Result:
It's not giving comma between two objects and brakets [] at the start and at the end.
set my sql char set after mysql_connect query like this...
this problem was occurring due to Gujarati font
$con = mysql_connect($host,$username,$password) or die(mysql_error());
mysql_set_charset('utf8mb4',$con);
I am working on web services where am using json_encode() to send my response .
It is working fine for every ther web service but I am getting json_encode(): type is unsupported, encoded as null for the following code only.
public function getjobdetailsAction()
{
$this->_helper->layout ()->disableLayout ();
$this->_helper->viewRenderer->setNoRender ( true );
$handle = fopen ( 'php://input', 'r' );
$jsonInput = fgets ( $handle );
$params = Zend_Json::decode ( $jsonInput );
if($params['user_id'] != "" && $params["job_id"] != "")
{
$job_id = $params["job_id"];
$jobObj=Extended\job::getRowObject( $job_id );
//check if job obj exist only then send job array to view.
if($jobObj)
{
$job_detail_r = array();
$job_detail_r['job_id'] = $job_id;
$job_detail_r['job_created_by'] = $jobObj->getIlookUser()->getId();
$job_detail_r['job_title'] = $jobObj->getJob_title();
$job_detail_r['url_fields'] = $jobObj->getUrl_fields();
$job_detail_r['job_reference'] = $jobObj->getJob_reference();
$job_detail_r['company_name'] = $jobObj->getCompany()->getName();
$job_detail_r['responsibilities'] = $jobObj->getResponsibilities();
$job_detail_r['industry_name'] = $jobObj->getIndustryRef()->getTitle();
$job_detail_r['skills_expertise'] = $jobObj->getSkills_n_expertise();
$job_detail_r['country'] = $jobObj->getCountryRef()->getName();
if( $jobObj->getState() )
{
$job_detail_r['state'] = $jobObj->getState()->getName();
}
else
{
$job_detail_r['state'] = "";
}
if($jobObj->getCity())
{
$job_detail_r['city'] = $jobObj->getCity()->getName();
}
else
{
$job_detail_r['city'] = "";
}
//$job_detail_r['job_function'] = $jobObj->getJobFunction()->getDescription();
$job_detail_r['job_description'] = $jobObj->getJob_description();
$job_detail_r['company_description'] = $jobObj->getCompany_desc();
if($jobObj->getSalaryRange())
{
$job_detail_r['salaryRange'] = $jobObj->getSalaryRange()->getCountryRef()->getCurrency_symbol()." ".$jobObj->getSalaryRange()->getMin_salary()." - ".$jobObj->getSalaryRange()->getMax_salary();
}
else
{
$job_detail_r['salaryRange'] = "";
}
$job_detail_r['jobType'] = $jobObj->getJobType()->getName();
//$job_detail_r['experienceLevel'] = $jobObj->getExperieneceLevel()->getMin_experience()." - ".$jobObj->getExperieneceLevel()->getMax_experience()." Years";
if($jobObj->getExperieneceLevel())
{
$job_detail_r['experienceLevel'] = $jobObj->getExperieneceLevel()->getDescription();
}
else
{
$job_detail_r['experienceLevel'] = "";
}
$job_detail_r['job_creator_image'] = Helper_common::getUserProfessionalPhoto( $jobObj->getIlookUser()->getId() );
$job_detail_r['time_of_post'] =$jobObj->getCreated_at()->format("Y-m-d H:i:s");
$job_detail_r['job_posted_by'] = $jobObj->getJob_posted_by();
$job_detail_r['apply_from'] = $jobObj->getApply_from();
if($jobObj->getJob_image() != "")
{
$job_detail_r['company_image'] = IMAGE_PATH."/jobs/".$jobObj->getJob_image();
}
else
{
$job_detail_r['company_image'] = IMAGE_PATH.'/no_image.png';
}
$job_detail_r['is_saved'] = Extended\saved_jobs::isJobSavedByMe($job_id,$params['user_id']);
$code = 200;
$msg = "Job details retrieved successfully";
$result = array("jobdetails"=>$job_detail_r);
}
else
{
$code = 301;
$msg = "Error in retrieving details";
}
}
else
{
$code = 301;
$msg = "Missing parameters";
}
echo Helper_common::successFailureMsgs($code,$msg,$result);
exit();
public static function successFailureMsgs( $code, $message, $result = array())
{
if($code == 200)
{
$result1 = array("Response"=>array("Code"=>$code,"Status"=>"OK","Message"=>$message,"result"=>$result));
}
else
{
$result1 = array("Response"=>array("Code"=>$code,"Status"=>"Error","Message"=>$message));
}
return Zend_Json::encode($result1);
}
In response I am getting correct response but the above error as well .
Please assist.
Thanks in advance.
For json_encode(), and therefore Zend_Json(), all types are accepted except resource.
So you have debbuger your table to see where the resource is located.
You can try something like this:
foreach ($job_detail_r as $k => $v){
if (is_resource($v))
echo $k . ' => ressource type = ' . get_resource_type($v);
}
My Json output generates;
[
{
"a1_id":"7847TK10",
"output2":"7847TK10",
"output4":"something",
"output5":"3stars.gif",
"output9": "269000",
...
etc. etc.
The google visualization api asks for a number format for the output9 element e.g.:
"output9": 269000 instead of "output9": "269000". How can I achieve this for this element?
My json.php generates the json output like this:
?>
{
"total": <?php echo $total ?>,
"success": true,
"rows": [
// Iterate over the rows
$nextRow= $result->nextRow();
$r = 1;
$info = array();
while ( $nextRow ) {
$nextColumn = $result->nextColumn();
// Has this column been printed already
if ( $unique )
{
$d = $result->getDataForField($unique);
if ( array_key_exists($d, $already) )
{
$nextRow= $result->nextRow();
continue;
}
$already[$d] = true;
}
echo '{';
// Iterate over the columns in each row
while ( $nextColumn )
{
// Get the variable
$variable = $result->getOutputVariable();
$name = $variable->getName(true);
$data = $result->getDataForField();
if ( !isset($info[$name]) ) {
$info[$name]['translate'] = $variable->shouldTranslate();
$info[$name]['type'] = $variable->getDataType();
$info[$name]['linkable'] = $variable->isLinkable();
}
// Translate the data if requested
if ( $info[$name]['translate'] ) {
$data = LQMTemplate::_($data);
}
$data = $variable->format($data, false);
$type = $info[$name]['type'];
if ( ($type == 'bool') or ($type == 'boolean') )
{
$data = $data ? '1' : '0';
echo "'$name':$data";
} elseif ( $encode ) {
// Can we use json_encode ?
// str_replace because some versions of PHP have a bug that will over escape forward slashes
echo "\"$name\":".str_replace('\\/', '/', json_encode($data));
} else {
$data = LQMUtility::jsonEscape($data, '"');
//echo "'$name':\"$data\"";
echo "\"$name\":\"$data\"";
}
// Conditionally print the next column
$nextColumn = $result->nextColumn();
if ( $nextColumn ) echo ",\n ";
}
// Conditionally print the next column
$nextRow = $result->nextRow();
echo $nextRow ? "},\n" : "}\n";
$r++;
}
unset($result);
echo ']}';
}
}
This depends on how you are generating your JSON.
For example, if you were using a Ruby backend, you could call:
"output9" => output9.to_i
There are various helper methods in different languages (e.g. Java and Javascript have parseInt() functions) to change a string into an integer.
Edit:
If your JSON is being generated by PHP, cast the string to an integer:
$json['output9'] = int($output9_value);
That should get rid of the quotation marks.