array to object codeigniter [REST API] - arrays

so i have an ouput data look like this
and this is my code
$var1[] = array('0' => $about_us,
'1' => $privacy,
'2' => $term_condition,
'3' => $copyright,
'4' => $faq);
$var2[] = array('0' => $voucher_redemption,
'1' => $contact_us);
$var3[] = array('0' => $about_point,
'1' => $earn_point,
'2' => $redeem_voucher);
$array["ABOUT"]=$var1;
$array["SUPPORT"]=$var2;
$array["POINT"]=$var3;
$final[]=$array;
$data["STATUS"] = "SUCCESS";
$data["MASSAGE"] = "LIST FOOTER TITLE";
$data["DATA"] = $final;
echo json_encode($data);
the problem is i want to return about [{"0":"about us"}] not only array

Make $var2 as an object, not an array
$var2= new stdClass();
$var2->0 = $voucher......

$result = array();
foreach($todo->result() as $hasil) {
$result[] = array(
'id_todo' => $hasil->id_todo,
'tanggal_input' => $hasil->tanggal_input,
'mapel' => $hasil->mapel,
'catatan' => $hasil->catatan
);
}

we can force that json_encode uses an object
json_encode($data, JSON_FORCE_OBJECT)

Related

How to access data from a query to a CGridView

I'm trying to use on my view a search made by CreateCommand to fill my CGridView, but I still need to pass as a dataProvider a CActiveDataProvider object.
Is there any way to transform my CreateCommand object into CActiveDataProvider or to do the same query directly as a CActiveDataProvider?
This is the view
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id' => 'credenciado-grid',
'dataProvider' => $model->search(),
'filter' => $model,
'afterAjaxUpdate' => "loadAfterAjax",
'rowHtmlOptionsExpression' => 'array("style"=>"cursor: pointer","data-row-id" => $data->cre_id, "class" => "row_grid")',
'columns' => array(
'cre_razao_social',
array(
'header'=>'Status',
'name'=>'cre_ativo',
'value'=>'Status::getStatus($data->cre_ativo)',
'filter'=>array(true => 'ATIVO',false => 'INATIVO'),
'filterHtmlOptions'=>array('class'=>'col-sm-2'),
),
),
)); ?>
This is the controller
$model = new Credenciado('getValoresCredenciadosByConvenioRank');
$model = new CArrayDataProvider($model, array());
// pe($model);
$modelEst = new Estabelecimento('search_adm');
// pe($model);
$modelEst->unsetAttributes();
if (isset($_GET['Estabelecimento']))
$modelEst->setAttributes($_GET['Estabelecimento']);
// $model->unsetAttributes();
// if (isset($_GET['Credenciado']))
// $model->setAttributes($_GET['Credenciado']);
$this->render('listar',array(
'model' => $model,
'modelEst' => $modelEst,
'mes1' => $mes1,
'mes2' => $mes2,
'meses' => $meses,
'produto' => $produto,
'data' => $format,
'datas' => $date_unique,
'series' => $series,
'ano1' => $ano1,
'ano2' => $ano2
));
}
This is the Model
$q = Yii::app()->db->createCommand()
->select("
cre.cre_razao_social,
count(op.ope_id) as linhas,
par.par_data_vencimento,
pro.pro_codigo,
SUM(
CASE
WHEN date_trunc('month',par_data_vencimento) < date_trunc('month',now()) AND pro_codigo != 2 THEN
par.par_valor
WHEN pro_codigo = 2 THEN
op.ope_valor_parcela
ELSE
op.ope_valor_parcela
END
) as total_carteira")
->from("operacao op")
->join('parcela par', 'par.par_operacao_ope_id = op.ope_id')
->join('pos po', 'po.pos_id = op.ope_pos_pos_id')
->join('rubrica_credenciado rub', 'rub.rub_id = po.pos_rubrica_credenciado_rub_id')
->join('credenciado cre','rub.rub_credenciado_cre_id = cre_id')
->join('produto pro', 'pro.pro_id = rub.rub_produto_pro_id')
->join('matricula ma', 'ma.mat_matricula = op.ope_matricula AND ma.mat_convenio_con_id = '.Yii::app()->user->convenioid.' ')
->where('op.ope_con_id = :con_id', array(':con_id' => $con_id));
$q->andWhere(
"(par.par_data_vencimento between :datamin and :datamax and ope_status in('E','S'))
OR
(par.par_data_vencimento between :datamin and :datamax AND par.par_num_parcela = op.ope_qtde_parcelas AND op.ope_status = 'Q')
",
array(':datamin'=>$datamin, ':datamax'=>$datamax));
if(Yii::app()->user->sistema != 1) {
$q->andWhere('rub_consignavel = true');
}
$q->order('par.par_data_vencimento', 'ASC');
//$q->andWhere(array('in', 'ope_status', array('E','S')));
$q->group('cre.cre_razao_social, pro.pro_codigo, par.par_data_vencimento');
$q->queryAll();
This is the error
exception 'CException' with message 'CArrayDataProvider and its behaviors
do not have a method or closure named "search".' in
/var/www/html/yii/framework/base/CComponent.php:266
Stack trace:
you are making a mistake in your view. In your controller you are already passing object of CArrayDataProvider (i.e $model) to your view, so you should not call search() function on $model variable. Instead you should create CArrayDataProvider object from CreateCommand in your model and pass the object of Credenciado as $model in your controller and call your query method in the view like $model-> getValoresCredenciadosByConvenioRank() to get the data provider. Then your view would look like this
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id' => 'credenciado-grid',
// call your query function to get data provider (this is the name of function that you have implemented in your model)
'dataProvider' => $model->getValoresCredenciadosByConvenioRank(),
'filter' => $model,
'afterAjaxUpdate' => "loadAfterAjax",
'rowHtmlOptionsExpression' => 'array("style"=>"cursor: pointer","data-row-id" => $data->cre_id, "class" => "row_grid")',
'columns' => array(
'cre_razao_social',
array(
'header'=>'Status',
'name'=>'cre_ativo',
'value'=>'Status::getStatus($data["cre_ativo"])',
'filter'=>array(true => 'ATIVO',false => 'INATIVO'),
'filterHtmlOptions'=>array('class'=>'col-sm-2'),
),
),
));
?>
Your controller would become this
$model = new Credenciado('getValoresCredenciadosByConvenioRank');
$model->unsetAttributes();
if (isset($_GET['Credenciado']))
$model->setAttributes($_GET['Credenciado']);
// pe($model);
$modelEst = new Estabelecimento('search_adm');
// pe($model);
$modelEst->unsetAttributes();
if (isset($_GET['Estabelecimento']))
$modelEst->setAttributes($_GET['Estabelecimento']);
$this->render('listar',array(
'model' => $model,
'modelEst' => $modelEst,
'mes1' => $mes1,
'mes2' => $mes2,
'meses' => $meses,
'produto' => $produto,
'data' => $format,
'datas' => $date_unique,
'series' => $series,
'ano1' => $ano1,
'ano2' => $ano2
));
}
And your model would return CArrayDataProvider instead of query result like this,
$queryResult = $q->queryAll();
// return data provider for view instead of query result
return new CArrayDataProvider($queryResult, array());
Hopefully this solution will solve your problem. Let me know if it works or if the problem still persists.

Array to DB::insert()->values(), which is in different order with the columns

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();

Why can I not achieve the same result with Collection::reduce() as with foreach?

I'm having trouble wrapping my head around CakePHP's Collection::reduce. Actually, it feels like I understand how it's supposed to work, but in reality it seems to work differently. I have a collection of entities, from which I'm trying to concat a number of strings, based on the contents of another array. The array has an ID, the collection has that ID as a sort of foreign ID. I loop through the array, and then in each loop I loop through the collection to find the entities which have a foreign ID matching the ID from the array. Implementing this with Collection::reduce gives a wildly different result from doing it with two foreach() loops. Anyway, here's the code:
public function reducetest() {
$this->render('test');
$groupby = ['a' => 1, 'b' => 2];
$array = [
array('id' => 'b', 'title' => 'array_tag_1'),
array('id' => 'a', 'title' => 'array_tag_2'),
array('id' => 'b', 'title' => 'array_tag_3'),
array('id' => 'a', 'title' => 'array_tag_4'),
array('id' => 'a', 'title' => 'array_tag_5')
];
$array_result = array();
foreach ($groupby as $key => $value) {
$array_result[$key] = '';
foreach ($array as $item) {
if ($key === $item['id']) {
// debug($array_result[$key] . $item['title'] . ", \n");
$array_result[$key] .= $item['title'] . ', ';
}
}
$array_result[$key] = trim($array_result[$key], ', ');
}
debug($array_result);
$collection = new Collection([
array('id' => 'b', 'title' => 'collection_tag_1'),
array('id' => 'a', 'title' => 'collection_tag_2'),
array('id' => 'b', 'title' => 'collection_tag_3'),
array('id' => 'a', 'title' => 'collection_tag_4'),
array('id' => 'a', 'title' => 'collection_tag_5')]
);
$collection_result = array();
foreach ($groupby as $key => $value) {
$collection_result[$key] = $collection->reduce(function ($string, $item) use ($key) {
if ($key === $item['id']) {
// debug($string . $item['title'] . ", \n");
return $string . $item['title'] . ', ';
}
}, '');
$collection_result[$key] = trim($collection_result[$key], ', ');
}
debug($collection_result);
}
The code with the two foreach() loops produces this result, as expected:
[
'a' => 'array_tag_2, array_tag_4, array_tag_5',
'b' => 'array_tag_1, array_tag_3'
]
The code that uses the reduce function gives this result - which is incomprehensible, to me:
[
'a' => 'collection_tag_4, collection_tag_5',
'b' => ''
]
Can you explain to me what I'm not getting here?

Drupal 7 create and send mailchimp campaign programmatically

How to create and send mailchimp campaign programmatically in drupal 7 ?
function kf_mailchimp_create_campaign() {
if (!isset($_GET['cron_key']) || ($_GET['cron_key'] != 'kQ7kOy4uRgPJd1FX1QQAERPeSYuPjp1qBW65goYcbDQ')) {
watchdog('kf_mailchimp', 'Invalid cron key !cron_key has been used to create campaign.', array('!cron_key' => $_GET['cron_key']));
drupal_exit();
}
$data['site_url'] = url('<front>', array('absolute' => TRUE));
$data['site_logo'] = theme_image(array(
'path' => drupal_get_path('theme', 'knackforge') . '/logo.png',
'alt' => 'KnackForge',
'attributes' => array('border' => 0),
));
$options = array(
'list_id' => $mc_list_id, // Change this to match list id from mailchimp.com.
'from_email' => variable_get('site_mail'),
'from_name' => 'KnackForge',
'to_email' => variable_get('site_name')
);
$type = 'regular';
$q = mailchimp_get_api_object(); // Make sure a list has been created in your drupal site.
$results = views_get_view_result('deal_mailchimp', 'page');
// Check to prevent sending empty newsletter
if (empty($results)) {
watchdog('kf_mailchimp', 'No active deals to send for today');
drupal_exit();
}
$data['deals'] = views_embed_view('deal_mailchimp', 'page');
$content = array(
'html' => theme('kf_mailchimp', $data),
);
$options['subject'] = t('Newsletter');
$options['title'] = $options['subject'] . ' - ' . date('r');
$options['tracking'] = array(
'opens' => TRUE,
'html_clicks' => TRUE,
'text_clicks' => TRUE
);
$options['authenticate'] = false;
$options['analytics'] = array('google'=>'atphga');
$cid = $q->campaignCreate($type, $options, $content);
watchdog('kf_mailchimp', 'Created campaign');
$result = $q->campaignSendNow($cid);
watchdog('kf_mailchimp', 'campaignSendNow() response !result', array('!result' => '<pre>' . print_r($result, 1) . '</pre>'));

Print terms from a specific vocab at page.tpl drupal 7

I used to have a function to create a custom menu by loading all terms from a specific vocab at drupal 6:
function _taxonomy_top_links($vid = NULL) {
$terms = taxonomy_get_tree($vid);
$taxos = array();
foreach ($terms as $term) {
$taxos[] = array('title' => $term->name, 'taxonomy/term/' . $term->tid, 'attributes' => array('rel' => 'tag', 'title' => strip_tags($term->description)));
}
return theme('links', $taxos, array('id' => 'menu-'. $vid, 'class' => 'menu clearfix'));
}
This doesn't work at drupal 7 which I guess related to the new field api. How do you grab all terms from a specific vocab to preprocess at page level?
Thanks for any help.
Most of your code should actually work fine, it's the theme part that is incorrect.
$terms = taxonomy_get_tree($vid, 0, NULL, TRUE);
$links = array();
foreach ($terms as $term) {
$uri = entity_uri('taxonomy_term', $term);
$link = array(
'title' => $term->name,
'href' => $uri['path'],
'attributes' => array('rel' => 'tag'),
);
$link += $uri['options'];
if (!empty($term->description)) {
$link['title'] = strip_tags($term->description);
}
$links['tid-' . $term->tid] = $link;
}
$variables = array(
'links' => $links,
'attributes' => array(
'id' => 'menu-' . $vid,
'class' => array('menu', 'clearfix'),
),
);
return theme('links', $variables);

Resources