I am pulling a queried result_array() and placing that array as the fields to select from in a form_multiselect(). What I can't seem to figure out is why the multi-select shows the array indexes followed by each queried result. Is this a problem with my array or are there form_multiselect options I am missing for the array indexes to not be shown?
And my code below:
public function get_tags() {
$this->db->select('tag_name');
$this->db->distinct();
$this->db->from('offers_tags');
$query = $this->db->get();
$tags = $query->result_array();
return $tags;
}
My controller:
$this->data['tags']=$this->offer_model->get_tags();
My view:
<div class="control-group">
<?= form_label('Tags: ', 'tag_targets', $label_attr);?>
<div class="controls">
<?= form_multiselect('tag_targets[]',$tags,'','id="geo-select"');?>
</div>
</div>
Maybe You have the order of the parameters wrong.
The first parameter will contain the name of the field, the second
parameter will contain an associative array of options, and the third
parameter will contain the value or values you wish to be selected
http://ellislab.com/codeigniter/user-guide/helpers/form_helper.html
You could also var_dump the array to check the values if you're not sure
I do not think you are specifying the options correctly.http://ellislab.com/codeigniter/user-guide/helpers/form_helper.html
you should be specifying the options like this:
$tags = array(
'tag1Value' => 'tag1Name',
'tag2Value' => 'tag2Name',
'tag3Value' => 'tag3Name',
'tag4Value' => 'tag4Name'
);
However what you are returning from your get_tags function is:
array(
0 => array('tag_name'=> 'Tag1'),
1 => array('tag_name'=> 'Tag2'),
2 => array('tag_name'=> 'Tag3')
)
Each result is a separate array contained with a wrapping array.
You can get the results into the format needed for form_multiselect by looping through the items and creating a new array. In your get_tags function you can do the following.
$tags = array();
foreach ($query->result_array() as $row)
{
$tags[$row['tag_name']] = $row['tag_name'];
}
return $tags;
Related
I'm trying to filter items from a database table
what I do is get the ids that I want to exclude and then through -> whereNotIn in laravel, I pass the ids
$idcontracts=array();
$idbike=array();
$biciCorretta = array();
$findcontract=Contract::whereRaw('? between data_inizio and data_fine', [$datainizio])->whereRaw('? between data_inizio and data_fine', [$datafine])->get();
foreach ($findcontract as $key) {
if (!in_array($key->id,$idcontracts)) {
array_push($idcontracts,$key->id);
}
}
foreach ($idcontracts as $idcontract) {
$bike_contracts=DB::table('bike_contract')->where('contract_id',$idcontract)->get();
foreach ($bike_contracts as $bike_contract) {
if (!in_array($bike_contract->bike_id,$idbike)) {
array_push($idbike,$bike_contract->bike_id);
}
}
}
$notid=implode("', '",$idbike);
up to this point I have no problem.
the result of "implode" gives me the ids I want to remove
this is the result of $idbike and $notid:
this is the query I write to exclude the ids found:
$bikes = Bike::with('category')->whereNotIn('id', [$notid])->orderBy('category_id')->get();
the problem is that it doesn't exclude me the ids passed with $notid
but if I manually pass the ids, it removes them instead:
$bikes = Bike::with('category')->whereNotIn('id', [40,41,34,36,39])->orderBy('category_id')->get();
am I doing something wrong?
You shouldn't implode $notid, that makes it a string and Laravels whereNotIn() already does that for you.
->whereNotIn('id', $idbike)
And remove the $notid parameter, as it is not needed.
implode will return in string, and because of that it will not work correctly, you should pass it as array instead.
If you print data
$idbike =[40,41,34,36,39];
print_r($idbike);
Output will be Array
Array
(
[0] => 40
[1] => 41
[2] => 34
[3] => 36
[4] => 39
)
and if you print below code
$notid=[implode(",",$idbike)];
print_r($notid);
The output will be
Array
(
[0] => 40,41,34,36,39
)
So your query become
->whereNotIn('id', ["40,41,34,36,39"])
so laravel searching for id of "40,41,34,36,39". so its not returning result
So you can pass array directly to wherenotin
->whereNotIn('id', $idbike)
Laravel, whereNotIn method removes elements from the collection that have a specified item value that is contained within the given array. That means you have to pass an array
So, idbike is the array you mentioned
$bikes = Bike::with('category')->whereNotIn('id', idbike)->orderBy('category_id')->get();
I have an object where there are all my articles.
I'm currently looping my object to fill an array where I create an associative table for each article.
In my object I also have a Categories object and I would like to add the label of each category at the end of each associative array previously completed, but
I don't know how to do that.. In the Categories object there may be multiple labels.
My code :
$articles = $this->entityManager->getRepository('SGBundle:Article')->findBy([], ['id'=>'desc']);
$arrayCollection = [];
foreach($articles as $article) {
$arrayCollection[] = [
'id' => $article->getId(),
'date_publication' => $article->getDatePublication(),
...
];
foreach($article->getCategories() as $categorie) {
$arrayCollection[] = ['categorie' => $categorie->getLibelle()];
}
}
On my screenshot, for each article there is an array with 36 values and an array with 1 value and I would like this table to be in the table where there are 36 values. It's possible ?
First gather categories, then add'em to article item:
foreach($articles as $article) {
$categories = [];
foreach($article->getCategories() as $categorie) {
$categories[] = $categorie->getLibelle();
}
$arrayCollection[] = [
'id' => $article->getId(),
'date_publication' => $article->getDatePublication(),
...
//
'categorie' => $categories,
];
}
If the article.categories field is marked as lazy, then it won't be hydrated by default and the $article->getCategories() will perform a new query on each loop round.
Instead of a simple findBy, you might want a custom DQL query in this case to optimize this and get the exact array you want in one single request.
Also note that your current query is fetching all articles of your database. While this is probably your purpose, keep in mind that this could get pretty heavy with the data growing. In most cases, this kind of query should be paginated.
I have the following function which should return all the tournaments and corresponding rounds inside an array.
When I call the function inside the body using a print_r I get only one tournament and round returned, however there are multiple tournaments and rounds. It is like the loop exits after only one iteration
function getTournaments(){
global $db;
$sql = "SELECT tournament, weekNum
FROM schedule
GROUP BY tournament";
$stmnt = $db->prepare($sql);
$stmnt->execute();
$tournaments = $stmnt->fetchAll();
$data = array();
foreach($tournaments as $tournament){
$data = array('tournament' => $tournament['tournament'], 'round' => $tournament['weekNum']);
}//foreach
return $data;
}//function
print_r(getTournaments());
Database dump
Here you can see the corresponding mysql statement run on the db
My output / Problem
As you can see on image below I only get one tournament and round returned when doing print_r, why am I not getting all tournaments and rounds returned inside the function array? Am I missing something here?
you over write $data in the loop you want to create new arrays (multidimensional):
$data[] = array('tournament' => $tournament['tournament'], 'round' => $tournament['weekNum']);
You should have used $data as an array :)
Use this
$data[] = array('tournament' => $tournament['tournament'], 'round' => $tournament['weekNum']);
instead of
$data = array('tournament' => $tournament['tournament'], 'round' => $tournament['weekNum']);
I have an array of the names of my POST variables to use when I update a row in my database.
$jobs = array( "proposal_id",
"will_provide",
"general_scope",
"per_bid",
"job_type");
Using this style my table is called jobs and each value in the array is a column id.
I want to edit this array so each item (column id) contains a single _POST Value
Then I have a function that uses the variables to create generic queries.
function save_data($jobs) {
foreach ($jobs as $job)
{
$job[$job[$i]] = _$Post[$job];
or
Table_name[column] = cell value;
...
...
...
I would like to be able to save $values into the post variables associated to it. Something like
For example if I was going to manually create this array it would look like
$jobs = array('proposal_id' => '12345678','title_of_project' => 'aTitle','creator' => 'aUser','last_modified' => '0000-00-00','date_created' => '0000-00-00','price' =>'1000');
This should be what you're looking for:
$jobs = array( "proposal_id",
"will_provide",
"general_scope",
"per_bid",
"job_type");
$jobValues = array();
foreach($jobs as $job) {
$jobValues[] = isset($_POST[$job]) ? $_POST[$job] : null;
}
$jobs = array_combine($jobs, $jobValues);
Trying to produce a bulleted list from text field in MySQL - I have the bullets in the DB field : I'm pulling data into the array $products, I need the string in array to be formatted as a bullet list in the products $Keyfindings2 results
<?php
/* This controller renders the category pages */
class CategoryController{
public function handleRequest(){
$cat = Category::find(array('id'=>$_GET['category']));
if(empty($cat)){
throw new Exception("There is no such category!");
}
// Fetch all the categories:
$categories = Category::find();
// Fetch all the products in this category:
$products = Product::find(array('category'=>$_GET['category']));
// $categories and $products are both arrays with objects
$Keyfindings2 = explode('•', $products);
echo "<ul style=\' list-style-type:upper-roman;\'>\n";
foreach( $Keyfindings2 as $item )
{
echo "<li>$item</li><br />\n";
}
echo "</ul>";
render('category',array(
'title' => 'Browsing '.$cat[0]->name,
'categories' => $categories,
'products' => $Keyfindings2
));
}
}
?>
UPDATE: now getting 'undefined variable' in other part of code on line 1:
<li <?php echo ($active == $category->id ? 'data-theme="a"' : '') ?>>
<a href="?category=<?php echo $category->id?>" data-transition="fade">
<?php echo $category->name ?>
<span class="ui-li-count"><?php echo $category->contains?></span></a>
</li>
You problem is quite simple: you are using explode on the wrong thing.
If your code/comments is right $products is an array and you explode it. You probably have your PHP error level too low because this produce a PHP warning: PHP Warning: explode() expects parameter 2 to be string, array given in php shell code on line 1
So from there 2 solutions: either $products is an array of strings and you can do
function myExplode($product) {
return explode('•', $product);
}
$Keyfindings2 = array_map('myExplode', $products);
or $products is an array of objects (as your code comment suggests) and you go with:
function myExplode($product) {
// well actual the name of the field or method to call really depends on your
// code and there is no way we can tell it with what we have on your post
// so consider this an example
return explode('•', $product->productFieldContainingList);
}
$Keyfindings2 = array_map('myExplode', $products);
With either solution the goal is the same: to apply explode on the correct data, not on an array containing that data.