how to use more than one variable in a group array? - php

I currently have the following code, it works great, but I've never tried to do anything more complex with this sort of thing. I'm wondering how I can add more variables to my result output.
$check_alt_sizes = mysqli_query($link, "SELECT model, version, size, category FROM items WHERE model = '$model' AND size != '$category' AND id != '$item_id'");
if (mysqli_num_rows($check_alt_sizes) >= 1) {
$group = array();
while ($row = mysqli_fetch_assoc($check_alt_sizes)) {
$group[ $row['category'] ][] = $row;
}
then later
foreach ($group as $sizes => $alt_size_urls) {
foreach ($alt_size_urls as $alt__size_url) {
echo "<a href='/items/"; echo "$alt_size_url[slug]"; // slug set elsewhere
echo "'>";
echo "$sizes</a>";
}
}
}
Now the $sizes part displays a list of sizes that I have gotten from grabbing $row['category'] in the initial $group from the query. What I would like to know is, how can I add more variables to this group, I've only ever dealt with doing it this way, never expanding it.
Currently it displays
Alternate Sizes:
size1
size2
but I would like to be able to add version as well, such as
Alternate Sizes:
Version1 - size1
Version2 - size1
Version3 - size2
I tried doing this:
echo $row['version']; echo "$sizes</a></p></li>";
But that just uses the first version found and applies it to every item. obviously because $sizes is looping and the version echo is not. How do I go about doing this?

I modified your source code with this one:
$group_size = "";
foreach ($group as $sizes => $alt_size_urls) {
$group_size .= "Alternate Sizes: <br>";
$ctr = 0;
foreach ($alt_size_urls as $alt__size_url) {
$group_size .= "<a href='/items/' " . $alt_size_url[slug] . (++$ctr) . "'>" . $sizes . "</a><br>";
}
}
echo $group_size;

Related

populate feed even if no images in PHP

I need to populate an ecommerce feed with extraimages
here is the header :
|image_1|image_2|image_3|
I've a table where I store or not, extra images for one product.
So I make a request to see if there are some extra images, with an sql limit of 3 as I only want 3 images max in my feed.
What I need is to populate the feed with empty pipes if there are no images and I don't know the logic to do that.
The output would be, for example, like this if I have 2 extra images :
|url/image_1.jpg|url/image_2.jpg|| <- empty pipe to match the header of 3
or only one image :
|url/image_1.jpg|||
My code so far :
$products_extra_images_query = tep_db_query(
"SELECT products_extra_image, products_extra_images_id
FROM " . TABLE_PRODUCTS_EXTRA_IMAGES .
" WHERE products_id='" . (int)$row->id . "' LIMIT 3");
if (tep_db_num_rows($products_extra_images_query) >= 1){
// there are some extra_images
while ($extra_images = tep_db_fetch_array($products_extra_images_query)) {
$output .= $extra_images['products_extra_image']."|" ;
}
}
thanks for your help.
Sebastien
Create an array of 4 and put your image path into it, then implode it into a string separated by "|".
$images = array_fill(0,4,null);
$idx = 0;
if (tep_db_num_rows($products_extra_images_query) >= 1) {
// there are some extra_images
while ($extra_images = tep_db_fetch_array($products_extra_images_query)) {
$images[$idx] = $extra_images['products_extra_image'];
$idx++;
}
}
$output .= implode($images, '|');
If I understood correctly then you could try an approach like this ~ though using non-standard names such as tep_db_fetch_array perhaps confuse the issue?
$rows = tep_db_num_rows( $products_extra_images_query );
if ( $rows > 0 ){
$output=[];
/* add found records to the `output` array rather than a string - or, use `fetch_all` */
while( $extra_images = tep_db_fetch_array($products_extra_images_query)) {
$output[]=$extra_images['products_extra_image'];
}
/* an odd looking loop but should add extra `pipe` chars when there are not 3 results */
for( $i=0; $i < ( 3 - $rows ); $i++ )$output[]='';
echo '|' . implode('|',$output) . '|';
}

Accessing results from collect() using neo4j-php-client

The below displays:
Marlena has 12 paintings (which is basically from the docs)
How do I access the data in collect(Paintings)
ex: title
$query = "MATCH (n:Artist)-[:PAINTED]->(Painting) RETURN n.first_name, collect(Painting) as paintings";
$result = $client->run($query);
foreach ($result->getRecords() as $record) {
echo sprintf('%s has %d paintings', $record->value('n.first_name'), count($record->value('paintings')));
echo '<br/>';
}
I would like to display:
Artist Name:
painting title
painting title
etc
I assume this data can be pull from either Painting or paintings. I am just unsure how to put together the query. It will display using print_r and the record so I know the data is coming through.
This should work for you:
$query = "MATCH (n:Artist)-[:PAINTED]->(Painting) RETURN n.first_name, collect(Painting) as paintings";
$result = $client->run($query);
foreach ($result->getRecords() as $record) {
echo sprintf('%s has %d paintings:<br/>', $record->value('n.first_name'), count($record->value('paintings')));
foreach ($record->value('n.paintings') as $painting) {
echo sprintf('- %s<br/>', $painting->value('title'));
}
echo '<br/>';
}
a) I suggest you alias your return values, it is easier to fetch them at the driver level
b) The paintings record value returns an array of Node objects, thus is iterable, no need to count for doing the for loop :
$query = "MATCH (n:Artist)-[:PAINTED]->(Painting) RETURN n.first_name as firstName, collect(Painting) as paintings";
$result = $client->run($query);
foreach($result->records() as $record) {
echo sprintf('%s painted %d paintings', $record->get('firstName'), count($record->get('paintings'))) . PHP_EOL;
foreach ($record->get('paintings') as $painting) {
echo sprintf('%s - %d views', $painting->value('title'), $painting->value('views')) . PHP_EOL;
}
}
I ended up getting it to work with the following:
foreach ($result->getRecords() as $record) {
$fname = $record->values()[0]->get('first_name');
$lname = $record->values()[0]->get('last_name');
echo '<strong>'.$fname.' '.$lname.' painted:</strong><br/>';
for ($x = 0; $x < count($record->values()[1]); $x++) {
print_r($record->values()[1][$x]->get('title'));
echo ' - ';
print_r($record->values()[1][$x]->get('views'));
echo ' views<br/>';
}
echo '<br/>';
}
Which provides the following output:
First Name Last Name painted:
Lumine - 86 views
Pooled Water - 69 views
Still Lake - 125 views
Final Notes
I actually tried code similar to what you suggested during my struggle to get this working. I'm a bit confused why it does not.
So I'm left wondering. Is what I come up with acceptable?

(PHP+MySQL) How can I echo the column name on a specific condition?

I am using PHP 5.4 with a MySQL database.
This database represents a media library. The table I'm dealing with has one column, "Title", with obvious contents, and then a series of boolean columns, representing the availability of that title on a given platform. So a row looks like
TITLE: "Curb Your Enthusiasm: The Game"
PS4: 0
Atari 2600: 1
Dreamcast: 0
And so on.
The PHP code I would like to write be, in pseudocode,
Echo row[0] (title)
Cycle through other cells in the row
If the cell is '0' or NULL, do nothing
But if the cell is '1', echo the name of that column
So the result would be the echoing of
Curb Your Enthusiasm: The Game (Atari 2600, WonderSwan, Saturn)
It's the fourth statement that I can't quite work out. It seems to require the function mysqli_fetch_field, but I'm not sure of the syntax, and nothing I try after googling quite works.
I'd really appreciate any advice or examples someone could offer!
$database = mysqli_connect(SERVER,USERNAME,PASSWORD,'games');
$query = mysqli_query($database,"SELECT * FROM games` WHERE NAME LIKE '%ZELDA%'");
while ($row = mysqli_fetch_row($query)) {
echo $row[0]; // Echo title
for ($i=0;$i<sizeof($row);$i++) {
if ($row[$i] === '1') {
// ???????
}
}
}
Here is some rough untested code that should hopefully get you going.
while ($row = mysqli_fetch_assoc($query)) {
$columns = array(); // this will track the additional columns we need to display
foreach($row AS $column => $value) {
if($column == "title") {
echo $value; // this is the title, just spit it out
continue;
}
if($value == 1) {
// We have a column to display!
$columns[] = $column;
}
}
if(count($columns)) {
// We have one or more column names to display
echo " (" . implode(", ",$columns) . ")";
}
}
Some things to point out:
Using mysqli_fetch_assoc will allow you access to column names along with the values, which is useful here.
Keep track of the columns you want to display in an array first, this makes it easier at the end of each loop to format the output.
Sounds like you can do something like this:
// Simulates DB fetch
$titles = array(
array(
'TITLE'=>'Curb Your Enthusiasm: The Game',
'PS4'=>0,
'Atari 2600'=>1,
'Dreamcast'=>0
),
array(
'TITLE'=>'Curb Your Enthusiasm: The Book',
'PS4'=>1,
'Atari 2600'=>1,
'Dreamcast'=>0
)
);
foreach($titles as $title){
// get supported platforms
$supportedPlatforms = array();
foreach($title as $titleAttribute=>$titleValue){
if($titleAttribute != 'TITLE' && $titleValue == 1)
$supportedPlatforms[] = $titleAttribute;
}
echo $title['TITLE'] . ' (' . implode(', ', $supportedPlatforms) . ')' . "<br>";
}
Try running it here: http://phpfiddle.org/lite/code/pr6-fwt

foreach with in a foreach php

Hi i have a script in which there is a foreach within a foreach. The first foreach is used for id which is unique, but the second foreach used is for related images of a product which should loop according to the number of images. However, it restricts me to fetch only one related image, how can i get all related images?
$i=0;
foreach ($collection as $product_all) {
//echo $product_all->getId().'<br/>';
if($i==10) break;
$id = $product_all->getId();
$neew = Mage::getModel('catalog/product')->load($id);
//echo'<pre>';
echo 'active products id ===='.$neew ->getId().'<br/>';
echo 'active products name ===='.$neew->getname().'<br/>';
echo 'active products style_ideas ===='.$neew->getstyle_ideas().'<br/>';
echo 'active products size and fit ===='.$neew->getsize_fit().'<br/>';
echo 'active products short description ===='.$neew->getshort_description().'<br/>';
echo 'active products description ===='.$neew->getdescription().'<br/>';
//print_r($neew);
if (count($neew->getMediaGalleryImages()) > 0){
$i = 0 ;
$j = 0 ;
foreach ($neew->getMediaGalleryImages() as $_image){
$relative_image = Mage::helper('catalog/image')->init($neew->getProduct(), 'image', $_image->getFile())->resize(2000);
$relative_image1 = str_replace('/webApps/migration/productapi/new/','/',$relative_image);
//echo 'relative_image => '.$relative_image1.'<br/>';
$relative_image_save = $relative_image1 ;
$relative_image_save1 = explode('/', $relative_image_save);//explode / to get only image name
$end1 = end($relative_image_save1);
$relative_image3 = $end1;
//$handle1 = fopen( $relative_image3, 'w') or die('Cannot open file: '. $relative_image);
$path12 = '/mnt/aviesta/development/webApps/migration/productapi/new/'.'sku-'.$neew->getsku().'_' .$i++.'.jpg';
copy($relative_image_save, $path12);
echo 'relative image with sku path_'.$j++.' ====>'.$path12.'<br/><br/>';
}
}
$i++;
}
From your code i think the problem can be solved by initializing an array before your 2nd foreach loop , and storing the images in that array can help you out in fetching all the images....This is what i understood from your question. If this is correct.., than the below code may work....
foreach()
{
//Your code....
$image_list = array();
$i = 0;
foreach()
{
// Your usual code
$image_list[$i] = your_image;
//storing images one-by-one in your variable..
$i++;
}
}
You can later return the variable or just print_r(); to get the output
i think i have post the question in little hurry, the script works fine , for the initial products there was a single images for the products but for the newer products there are multiple images and the script works fine , thanks to all of you to respond the post .....

i need a little help on foreach

This is my cats in mysql
cats_id cats_position cats_parentid
1 1> 0
2 1>2> 1
3 3> 0
4 1>2>4> 2
and i am trying to create a navigation like:
index > cars > fiat > punto
from
cat=4&parent=2&position=1>2>4>
I end up getting:
Index carcarcarcar
and my php knowledge is not enough to finish this code. can you help me please.
<?php
$position = trim($_GET['position']);
$pieces = explode(">", $position);
$i=0;
foreach($pieces as $piece){
$result = mysql_query("SELECT * FROM cats
WHERE cats_id='".$pieces[$i]."'");
while($row = mysql_fetch_array($result))
{
$piecesid[$i] = $row['cats_id'];
$piecesname[$i] = $row['cats_name'];
$piecesposition[$i] = $row['cats_position'];
}
$i++;
}
?>
Index
<?php $i=0; foreach($pieces as $piece){
if($i=0)
$parent=0;
else
$parent=$placesid[$i-1];
echo '<a href="cats.php?cat='.$piecesid[$i].'&parent='.$parent.'&position='.$piecesposition[$i].'">'.$piecesname[$i];
}
Your first error is a missing semicolon here:
$i++;
The second bug is a missing dot after $parent in the echo line:
'&parent='.$parent.'&position='
The third (unexpected end) error will become apparent when you started to indent your code correctly. It's also bad style to omit the curly braces, because that makes it more difficult to find precisely such errors.
And lastly: when posting on Stackoverflow, include the full error message (which always mentions the line number!)
I believe this is what he is looking for:
Create a mysql table with id, parent_id, and name fields.
When a category is a "child" of another, that others parent_id field should be set accordingly, I see you already have something to that effect.
Use this code, setting $cat via $_GET['cat'] or something.
<?php
$cat = mysql_real_escape_string($_GET['cat']);
$res = mysql_query("select id,name,parent_id from categories where id = '$cat'");
$breadcrumb = array();
while ($category = mysql_fetch_object($res) {
$breadcrumb[] = "" . $category->name . "";
if ($category->parent_id != 0) {
$res = mysql_query("select id,name,parent_id from categories where id = '{$category->parent_id}'");
}
}
echo join(" > ", array_reverse($breadcrumb));
?>
You have not closed your foreach in the last php section
<?php $i=0; foreach($pieces as $piece){
if($i=0)
$parent=0;
else
$parent=$placesid[$i-1];
echo '<a href="cats.php?cat='.$piecesid[$i].'&parent='.$parent'&position='.$piecesposition[$i].'>'.$piecesname[$i];
//Missing } here
?>
you're missing a } at the end. Just put a } after the last line like this:
echo '<a href="cats.php?cat='.$piecesid[$i].'&parent='.$parent'&position='.$piecesposition[$i].'>'.$piecesname[$i];
}
By the way, you don't need cats_position in your table.
To handle hierarchical data like this you can use a nested set (http://en.wikipedia.org/wiki/Nested_set_model) or just rely on the parent_id.
The advantage of this is, that you for example don't need multiple parameters in your get query. Instead of
cat=4&parent=2&position=1>2>4>
you then archieve the same with:
cat=4

Categories