Ok, what i have is a PHP array that looks like this:
Array
(
[0] => Array
(
[label] => 1
[value] => Value example
)
[1] => Array
(
[label] => 10
[value] => Value example 2
)
[...]
)
Now, if i json_encode() this array, what i get is:
[
Object { label="1", value="Value example" },
Object { label="10", value="Value example 2" },
...
]
But to use it in jQuery Autocomplete i need the array to be like this:
[
{ label="1", value="Value example" },
{ label="10", value="Value example 2" },
...
]
I've read tons of pages without finding a solution...can someone help?
UPDATE FOR PETER:
Here's my code:
$results = array();
foreach ($temp as $tmp) {
$results[] = array(
'label' => $tmp['id'],
'value' => $tmp['it']
);
};
echo json_encode($results);
If it may be useful, $temp array is generated from the following Wordpress function:
$wpdb->get_results($query, ARRAY_A);
UPDATE FOR PETER 2
SCRIPT:
jQuery(document).ready(function($){
var temp_array = function(request, response) {
$.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'POST',
dataType: 'json',
data: {
'action': 'autocomplete_finder',
'data' : request.term,
},
success: function(data) {
//response(data);
console.log(data);
}
});
};
$('#containing').autocomplete({
source: temp_array,
minLength: 3,
select: function(event, ui) {
console.log('test')
}
});
});
HTML:
<input id="containing" style="width: 98%">
I just realized what simple mistake you did
Switch label with value:
$results = array();
foreach ($temp as $tmp) {
$results[] = array(
'label' => $tmp['it'],
'value' => $tmp['id']
);
};
echo json_encode($results);
and it will works
your array should look like this:
Array
(
[0] => Array
(
[label] => Value example
[value] => 1
)
[1] => Array
(
[label] => Value example 2
[value] => 10
)
[...]
)
Related
I need to post an array of data with the index number of the line. (If I send without the index in brackets, only the last item is being picked up by the server)
Problem is that js doesn't allow me to use brackets in the key name...
I tried to build a string with all the array data as key[0] : 'value' and than passed it in as one of the param, but that didn't work either.
Meteor.methods({
submit_order: function(){
var test = HTTP.call("POST", "https://example.com/api/",
{
headers:
{
"Content-Type": "application/x-www-form-urlencoded"
}
,
data : {ApiLogin:'login',
ApiKey:'key',
OrderNumber:'ReactTest1',
Items[0][ProductQty] : '1', <--- problem is here
Items[1][ProductQty] : '2'
},
},
function (error, result) {
if (!error) {
console.log(result);
} else{
console.log("http post error");
};
});
}
});
In PHP its written as follows:
'Items' => array(
1 => array(
'ProductQty' => 2,
),
2 => array(
'ProductQty' => 1,
),
3 => array(
'ProductQty' => 1,
)
),
You are close, you just need to set up the array in the following way:
{
ApiLogin:'login',
ApiKey:'key',
OrderNumber:'ReactTest1',
Items:[{ProductQty : '1'},{ProductQty : '2'}]
}
Hi folks! I'm trying to transfer data as array from the controller to the model, and then paste the data into the query builder, but the data must be in the same order as specified in the columns.
What options do I have?
And do you think this is a bad practice?
Controller:
$responseNotes = Model::factory('Notes')-> createTicket([
'description' => htmlspecialchars($_POST['description']),
'contact_id' => $_POST['contact_id'],
'pref_contact' => $_POST['pref_contact'],
'dog_id' => $_POST['document_id'],
'type' => $_POST['type'],
'owner_id' => Auth::instance()->get_user()->id,
'cc' => $_POST['cc-emails'],
'title' => $_POST['title']
]);
Model:
public function createNote(array $data)
{
$columns = [
'type',
'owner_id',
'cc',
'title',
'description',
'contact_id',
'pref_contact',
'dog_id'
];
if (!array_diff($columns, array_keys($data))) {
// All needed values exists
$result = DB::insert($this->NOTES, $columns)-> values($data)-> execute($this->SCHEMA);
}
return ($result) ? $result : false ;
}
Thanks to this answer. Solved this by:
// Order $data array according to $column.values
$orderedData = [];
foreach ($columns as $key) {
$orderedData[$key] = $data[$key];
}
$result = DB::insert($this->TICKETS, $columns)
-> values($orderedData)
-> execute($this->SCHEMA);
Why you don't use ORM Model?
in controller:
$responseNotes = ORM::factory('Notes')-> values([
'description' => htmlspecialchars($_POST['description']),
'contact_id' => $_POST['contact_id'],
'pref_contact' => $_POST['pref_contact'],
'dog_id' => $_POST['document_id'],
'type' => $_POST['type'],
'owner_id' => Auth::instance()->get_user()->id,
'cc' => $_POST['cc-emails'],
'title' => $_POST['title']
])
try{
$responseNotes->save();
} catch (ORM_Validation_Exception $ex) {
print_r($ex->errors('models'));
}
And don't use htmlspecialchars($_POST['description'])
In model class modify function (doc):
public function filters()
{
return array(
'description' => array( array('htmlspecialchars') ),
);
}
It looks like You have associative array with structure db_column=>value right? Than You can simply insert like this:
DB::Insert('table_name',array_keys($data))->values(array_values($data))->execute();
[0] => Array
(
[0] => name
[1] => email
[2] => contact
[3] => address
)
[1] => Array
(
[0] => santosh
[1] => santoshm9916#gmail.com
[2] => 9035619733
[3] => hennur
)
i want to access the [1] index(Email ID) from this array. please help......
Thank YOU
If you are doing javascript it could be done like this if you know what key to call for your data.
var arr = ([
["name","e-mail","contact","address"],
["santosh","santoshm9916#gmail.com","9035619733","hennur"],
["santosh2","santoshm991622222#gmail.com","90356197332","hennur2"],
["santosh3","santoshm9916#gmail.com","90356197333","hennur3"]
]);
console.log(arr[1][1]);
Your data :
$data = [[
'name',
'email',
'contact',
'address'
],
[
'santosh',
'santoshm9916#gmail.com',
'9035619733',
'hennur'
]
];
PHP Code:
$title = $data[0];
unset($data[0]);
$table = '<table border="1">';
$table .='<tr>';
foreach($title as $k=>$val){
$table.='<td>'.$val.'</td>';
};
$table.='<tr/>';
foreach($data as $key=>$val){
$table.='<tr>';
foreach($title as $k=>$v){
$table.='<td>'.$val[$k].'</td>';
}
$table.='</tr>';
}
$table.='</table>';
echo $table;
Output :
name email contact address
santosh santoshm9916#gmail.com 9035619733 hennur
Im am trying to create a controller that uploads a file for me but I always get the same result. The file isn't valid so he doesn't upload.
The function in my controller is:
$upload = new \Zend\File\Transfer\Transfer();
$upload->setDestination('./data/images/uploads/');
$rtn = array('success' => null);
if ($this->getRequest()->isPost()) {
$files = $upload->getFileInfo();
foreach ($files as $file => $info) {
if (!$upload->isUploaded($file)) {
print "<h3>Not Uploaded</h3>";
\Zend\Debug\Debug::dump($file);
continue;
}
if (!$upload->isValid($file)) {
print "<h4>Not Valid</h4>";
\Zend\Debug\Debug::dump($file);
continue;
}
}
$rtn['success'] = $upload->receive();
}
return new \Zend\View\Model\JsonModel($rtn);
The result is:
<h4>Not Valid</h4><pre>string(8) "files_0_"
</pre>{"success":false}
When I look at $files (print_r()) I get:
Array
(
[files_0_] => Array
(
[name] => logo_welcome.gif
[type] => image/gif
[tmp_name] => /private/var/tmp/phpiufvIc
[error] => 0
[size] => 62935
[options] => Array
(
[ignoreNoFile] =>
[useByteString] => 1
[magicFile] =>
[detectInfos] => 1
)
[validated] =>
[received] =>
[filtered] =>
[validators] => Array
(
[0] => Zend\Validator\File\Upload
)
[destination] => ./data/images/uploads
)
)
As you can see in ZF2 docs, file uploading with Zend\File\Transfer has been deprecated in favor of using the standard ZF2 Zend\Form and Zend\InputFilter features.
Having said that, you should use Zend\Filter\File\RenameUpload to move the uploaded file. You just need to attach the Zend\Filter\File\RenameUpload filter to your InputFilter specification, like that:
$this->add([
'name' => 'file',
'type' => 'Zend\InputFilter\FileInput',
'filters' => [
[
'name' => 'FileRenameUpload',
'options' => [
'target' => realpath('./data/uploads/'),
'randomize' => true,
'use_upload_extension' => true,
],
],
],
]);
And in your controller action:
if ($this->request->isPost()) {
$post = array_merge_recursive(
$this->request->getPost()->toArray(),
$this->request->getFiles()->toArray()
);
$form->setData($post);
if ($form->isValid()) {
// File uploaded and moved to data/uploads folder
}
}
Take a look in official documentation for a complete example.
No problem to use this function 'multiselect field' which show on this website:
http://www.grocerycrud.com/documentation/options_functions/field_type
$crud->field_type('fruits','multiselect',
array( "1" => "banana", "2" => "orange", "3" => "apple"));
Next step, i try to extract data from database to replace the 'array' in the formulae above but failed, pls advise.
$this->db->select('employeeNumber');
$a = $this->db->get('employees')->result();
$crud->field_type('firstName', 'multiselect', $a);
I'm getting result like
Array ( [0] => stdClass Object ( [employeeNumber] => 1002 )
[1] => stdClass Object ( [employeeNumber] => 1056 )
Hmm... how to make it into this format, any advise?:
array( "1" => "banana", "2" => "orange", "3" => "apple")
You need to actually do a foreach here. In our case you need to do something like this:
$this->db->select('employeeNumber');
$results = $this->db->get('employees')->result();
$employees_multiselect = array();
foreach ($results as $result) {
$employees_multiselect[$result->employeeNumber] = $result->employeeNumber;
}
$crud->field_type('firstName', 'multiselect', $employees_multiselect);
or it is even better if you have the name of the employer to do something like this:
$this->db->select('employeeNumber, employeeName');
$results = $this->db->get('employees')->result();
$employees_multiselect = array();
foreach ($results as $result) {
$employees_multiselect[$result->employeeNumber] = $result->employeeName;
}
$crud->field_type('firstName', 'multiselect', $employees_multiselect);