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.
Related
I have this foreach loop wich shows the supporters located in the post_meta from a custom post type. What I want to do is add pagination to the foreach loop. I have already found a way to decide how many supporters are shown by slicing the array, but now I am at a loss. And have no idea how to proceed.
Function to get the supporters array
function getSupporters($petitieID){
$support = get_post_meta(get_the_ID(), 'supporters', true);
if (!empty($support)){
return $support;
}}
Function to show the individual supporters in the array
function showSupporters($petitieID){
$supporters = getSupporters($petitieID);
if (!empty($supporters)){
foreach (array_slice($supporters, 0, 2) as $supporter){
$supporterID = $supporter->post_author;
the_author_meta('first_name', $supporterID);
}
}else {
echo 'no votes';
}
}
You could determine which page is currently shown in a GET variable in your address
.../supporters.php?page=1
Then you could set the offset of your array_slice function accordingly
$nItemsPerPage = 2;
$page = isset($_GET['page'])?$_GET['page']:1;
array_slice($supporters, $nItemsPerPage*($page-1), $nItemsPerPage)
I am trying to create an overview of product properties, for an invoice system.
So far, most things are comming together using classes and PDO.
I have the following issue.
In my class, i've created a function that builds my products array.
It loads some information from the database, to build this array.
This array, i want to use to display all the products i have selected:
$prod1 - $prod1Name - $prod1Descr - $prod1Price
$prod2 - $prod2name - $prod2Descr - $prod2Price
etc.
I figured that the Associative array would help me creating columns.
Though the problem is, that i do not understand a bit how to create multiple lines and columns this way.
I was thinking of something like:
$prod[1]["name"] - $prod[1]["descr"] - etc
Then to use this in a foreach loop to create as many new lines as required.
The only thing i could come up with is on my index.php (as shown below), cause using an index (the [1] defenition) does not seem to work the way i think it should be implemented.
For my understanding, i assigend the var in my class as an array, then redefine an array when loading the database information.
Could anyone tell me how i could try to solve this issue?
I have the following class:
<?
class Invoice{
var $vendorID;
var $product = array();
function product_array(){
global $db;
$query = $db->conn->prepare('
SELECT ProductName, ProductDescription, ProductDuration, ProductPriceInclVat, ProductPriceExclVat, ProductVatType
FROM products WHERE VendorID = :VendorID
');
$array = array (
'VendorID' => $this->vendorID
);
$query->execute($array);
$result = $query->fetchall();
if (empty($result)){
echo"Could not find any products matching your criteria.";
die;
} else {
foreach($result as $row) {
$this->product = array("Name" => $row['ProductName'],
"Description" => $row['ProductDescription'],
"Duration" => $row['ProductDuration'],
"PriceExclVat" => $row['ProductPriceExclVat'],
"PriceInclVat" => $row['ProductPriceInclVat'],
"VatType" => $row['ProductVatType']
);
}
}
}
}
?>
and then i have the following code on my index.php:
<?
$invoice = new Invoice();
foreach ($invoice->product as $key => $value){
echo $key . "<br>";
echo $value . "$value";
echo "<br>";
}
?>
When you are assigning the result arrays to the product property you are overwriting the array every time. You need to append to the array instead, so something like:
$this->product = array();
foreach($result as $row) {
$this->product[] = array(...);
}
Alternatively, you could just assign the results of fetchAll to the product property if you don't need to rename the field keys (or you could alias them in the SQL).
$query = $db->conn->prepare('
SELECT ProductName as Name,
ProductDescription as Description,
ProductDuration as Duration,
ProductPriceInclVat as PriceInclVat,
ProductPriceExclVat as PriceExclVat,
ProductVatType as VatType
FROM products WHERE VendorID = :VendorID
');
$array = array (
'VendorID' => $this->vendorID
);
$query->execute($array);
$product = $query->fetchall(PDO::FETCH_ASSOC);
The $product is now in the format you require.
After this you can avoid foreach loop in class invoice.
Other thing i noticed that you have made function product_array() which is not called,
so in index.php you are getting empty array (defined in class Invoice).
So in Invoice class it should be
$product = product_array()
and product_array function should return the value.
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;
Studying Programming Yii, I want to display the last 4 pages:
SiteController.php
public function actionStart()
{
$featured = Page::model()->findAllByAttributes(
array(),
$condition = 'featured = :featureId',
$params = array(
':featureId' => 1,
)
);
$this->render('/layouts/start/start', array('featured'=>$featured));
}
/layouts/start/start.php
<?php print_r($this->featured); ?>
The latter file does not display anything, and should be an array with the data, how do I get it?
$this->render('/layouts/start/start', array('featured'=>$featured));
Here, you are sending array(association array) of values to the View. You can access these values by calling the array Key.
So, your code should be
<?php echo print_r($featured); ?>
Another example.
$this->render('myView', array('myName'=>'Hearaman','myAge'=>25));
I'm sending my name and age to View. To show my name and age, i should call the keys
echo $myName;
echo $myAge;
Eliminate the $this for featured.
<?php echo print_r($featured, true); ?>
My code is pretty basic. I'm using an array to generate a datasheet for a product based on it's SKU and a filepath.
My array looks like this:
$a=array(
"/images/ManualSheets/factSheetCLASSIC.pdf"=>"KE800/6",
"/images/ManualSheets/factSheetMICRO.pdf"=>"KE800/12",
"/images/ManualSheets/factSheetSMALL.pdf"=>"KE4000/12",
"/images/ManualSheets/factSheetMEDIUM.pdf"=>"KE8000/12",
);
Where the first Key is the filepath, and the second Key is the SKU (as generated by the system) I then use an if/else to generate a button - so if a product is not in the array it returns a blank value and doesn't have a button which leads to nowhere
$factsheetweblink_url = array_search($product_sku,$a);
if ($factsheetweblink_url==false) {
echo " ";
}
else {
echo "<div class='productpagestockistBTN'>
<img src='/images/FactSheet_btn.png' >
</div>";
}
?>
This code works fine. The catch comes when I have products with different SKUs but the same datasheet file, (same brand and make but a different model). Currently I can only get it to work by uploading multiple copies of the datasheets with different names, but it's becoming a big waste of space.
I have tried using an array as a key to hold multiple values to the one key..
"/images/ManualSheets/factSheetMEDIUM.pdf"=> array("KE8000/12","KE7000/12"),
but it doesn't seem to be working... I'm not quite sure if I need to refine my if statement to search within the sub arrays as well or..?
Any help would be appreciated, thanks in advance.
You should use arrays like this:
$products = array(
0 => array(
"pdf" => "/images/ManualSheets/factSheetCLASSIC.pdf",
"skus" => array("KE800/6","KE900/6")
),
1 => array(
"pdf" => "/images/ManualSheets/factSheetCLASSIC3.pdf",
"skus" => array("KE100/6","KE200/6"))
);
This is because array_search returns just first row whit that key.
Then just do your own search function like:
function findBySku($items, $sku) {
$pdf = ""; // return empty if not found.
foreach($items as $row) {
if (in_array($sku, $row['skus'])) {
$pdf = $row['pdf'];
break;
}
}
return $pdf;
}
and call that function:
$pdf = findBySku($products, "some sku");