Show Different Divs based on query result - php

Here what I got in view
I want to show it as Separate divs based on vendor name
How can i Group the vandor names and Show in different divs ?

I don't know how the data is being stored/retrieved but here is how I might do such sorting - assuming the variable $rows is set contains an associative array of all rows (similar to the results of a basic database query) and assuming "vendor" is the column name for the vendors (TSZ, TSR, etc), "sku" is the name of the SKU column, and "store_price" is the name of the store price column:
<?php
$vendorData = [];
foreach( $rows as $row ) {
if( !isset($vendorData[$row['vendor']]) ) {
$vendorData[$row['vendor']] = '';
}
$vendorData[$row['vendor']] .= '<div class="sku">' .
$row['sku'] . '</div>' .
'<div class="price">' . $row['store_price'] . '</div>';
}
foreach( $vendorData as $vendorName => $vendorHTML ) {
echo '<div id="' . $vendorName . '" class="vendor">' .
'<h3 class="name">' . $vendorName . '</h3>' .
'<div class="data">' . $vendorHTML . '</div></div>';
}
?>

Here is thing what you need:-
$newDataRow = []
foreach($dataRows as $dataItemRow):
$newDataRow[$dataRows['vendor']][] = $dataItemRow;
endforeach;
$op = '';
foreach($newDataRow as $vandorName => $vandorItemData):
$op .= '<div class="vendor_item_group">';
$op .= '<div class="vendor_name">'.$vandorName.'</div>';
$op .= '<div class="item_group">';
foreach($vandorItemData as $record):
$op .= '<span>'.$record['sku'].'</span>';
$op .= '<span>'.$record['price'].'</span>';
endforeach;
$op .='</div>';
$op .= '</div>';
endforeach;
echo $op;
Output Should be like this:-
TSZ TSR
TSZ K377 TSR319
2300 2250
TSR319
2300

Related

Breaking with a divider if more than one inside foreach

$linkPairs returns the following:
array (size=2)
0 => string 'Test|https://www.test2.com' (length=26)
1 => string 'Test2|http://www.test2.com/' (length=27)
How would I be successful on breaking the links using a divider as this: Test | Test2 .. the format that I'm getting now is TestTest2.
So I have the following code:
$linkPairs = explode(",", $atts['link']); // separate the pairs
$output = '';
$output .= '<li class="slide">
<p><img src="' . esc_url($atts['image']) . '" alt="" /></p>
<p>'. $atts['headline'] .'</p>
<p>'. $atts['body'] .'</p>';
foreach($linkPairs as $linkPair) {
$pair = explode("|", $linkPair); // separate the title and url
$output .= '' . $pair[0] . '';
}
$output .= '</li>';
One method to do it, would be add the links to an array, and implode them with what you wish to have separate them:
$output .= '<li class="slide">
<p><img src="' . esc_url($atts['image']) . '" alt="" /></p>
<p>'. $atts['headline'] .'</p>
<p>'. $atts['body'] .'</p>';
$hrefs = array();// define and clean for this item
foreach($linkPairs as $linkPair) {
$pair = explode("|", $linkPair); // separate the title and url
$hrefs[] = '' . $pair[0] . '';
}
$output .= implode(' | ',$hrefs);// implode them here
$output .= '</li>';
The imploded pipe, is not to be confused with the original pipe used in the raw data you work with. You mentioned you wanted to space your hrefs with a pipe, so that is the example above.
Update your foreach to add the divider, then rtrim() the last one
$divider = ' | ';
foreach($linkPairs as $linkPair) {
$pair = explode("|", $linkPair); // separate the title and url
$output .= '' . $pair[0] . ''.$divider;
}
$output = rtrim($output,$divider);
since it's good to know all possible ways you can also do the following count number of elements inthe linkPairs array then track the array pointer location to know the last link so that you don't add | to the last entry. I have explained everything i added in comment infront of the line.
$linkPairs = explode(",", $atts); // separate the pairs
$output = '';
$output .= '<li class="slide">
<p><img src="' . esc_url($atts['image']) . '" alt="" /></p>
<p>'. $atts['headline'] .'</p>
<p>'. $atts['body'] .'</p>';
$li=count($linkPairs);//number of element of array
$i=1;//track the current location of array_pointer
foreach($linkPairs as $linkPair) {
if($i!=$li){
$symbol="|";//add | if the link is not the last link
}
else {
$symbol="";//add nothing if the link is the last link
}
$pair = explode("|", $linkPair); // separate the title and url
$output .= '' . $pair[0] . ''.$symbol;//$symbol is used to add | to the link
$i++;
}
$output .= '</li>';

How to create a SELECT element with an array of options using PHP? [duplicate]

This question already has answers here:
creating variable name by concatenating strings in php
(4 answers)
Closed 8 years ago.
Simple question, with im sure a simple answer, I just cant get it working!!
I have a function which will be passed one of 5 id's (for example "first", "second", ",third", "fourth" and "fifth").
Inside this function I want to refer to an array whose name is the id followed by _array (for example "first_array", "second_array" etc...)
How do I concatenate the id name passed to the function with the string "_array" ? I know how to do this in a string but not when referring to another variable!
To sum up i will have:
$i_d = "first" //passed to my function
$string = "_array"
and I want to link to an array called:
$first_array
EDIT
My code is the following:
$option_timescale = array ( "1"=>"Immediately",
"2"=>"1 Month",
"3"=>"2 Months",
"4"=>"3 Months",
"5"=>"4 Months",
"6"=>"5 Months",
"7"=>"6 Months",
"8"=>"No Timescale"
);
$option_bus_route = array ( "1"=>"1 minute walk",
"2"=>"5 minute walk",
"3"=>"10 minute walk",
"4"=>"No Bus Needed"
);
$option_train_stat = array( "1"=>"5 minute walk",
"2"=>"10 minute walk",
"3"=>"5 minute drive",
"4"=>"10 minute drive",
"5"=>"No Train Needed"
);
function select_box($k,$v){ //$k is the id and $v is the description for the select boxes label
$string = "option_"; //these two lines
$option_array =$string . $k; //are the troublemakers!
$buffer = '<select name="' . $k . '" id="' . $k . '">';
foreach ($option_array as $num=>$desc){
$buffer .= '<option value="' . $num . '">' . $desc . '</option>';
}//end foreach
$buffer .= '</select>';
$buffer .= '<label for="' . $k . '">' . $v . '</label>';
return $buffer;
}//end function
And the code which calls this function is:
function create_table($titles, $id) { //$titles is the relevant array from lists.php, $id is the id of the containing div
$select = array('timescale','bus_route','train_stat'); //'select' id list
$textarea = array('notes'); // 'textarea' id list
$buffer = '<div id="' . $id . '">';
foreach ($titles as $k=>$v) { //$k is the database/id/name $v is the description text
if (in_array($k,$select)){
$buffer .= select_box($k,$v);
}
else if (in_array($k,$textarea)){
$buffer .= text_box($k,$v);
}
else{
$buffer .= check_box($k,$v);
}
}
$buffer .= '</div>';
echo $buffer;
}
Add $ to eval the string.
$i_d = "first";
$string = "_array";
$myvar = $i_d . $string;
$$myvar = array('one','two','three');
print_r( $$myvar);

Print specific array value via function argument

$menu = array(
0 =>'top',
1 =>'photography',
2 =>'about'
);
<?php
function main_menu ($menu) {
$return = '<div class="menu_entry">' . PHP_EOL .'';
foreach( $menu as $key => $value)
{
$return .= '<a class="menu" href="index.php#' . $menu[$key] . '">' . $menu[$key] . '</a>' . PHP_EOL .'';
}
$return .= '</div>';
return $return;
}
?>
<?php echo main_menu($menu[1]); ?>
What i basically want to do is to pass a specific array value when i'm echoing out the menu.
I'm building a single page website with anchors and i want to pass value's so i can echo out the "top"-link.
I'm stuck at the point on how to pass the $key value trough the function.
**edit: I'm trying to print specific links. I want a function that is able to print out an link but i want to specify the link to print via the function argument.
for example:
<?php echo main_menu($key = '0'); ?>
result:
prints url: top
<?php echo main_menu($key = '2'); ?>
result:
prints url: photography
**
(A lack of jargon makes it a bit harder to explain and even harder to google.
I got my books in front of me but this is taking a lot more time than it should.)
You either need to pass the entire array and loop, or pass a single array item and not loop:
Single Item:
function main_menu ($menu) {
$return = '<div class="menu_entry">' . PHP_EOL .'';
$return .= '<a class="menu" href="index.php#' . $menu . '">' . $menu . '</a>' . PHP_EOL .'';
$return .= '</div>';
return $return;
}
echo main_menu($menu[1]);
Entire Array:
function main_menu ($menu) {
$return = '<div class="menu_entry">' . PHP_EOL .'';
foreach($menu as $value) {
$return .= '<a class="menu" href="index.php#' . $value . '">' . $value . '</a>' . PHP_EOL .'';
}
$return .= '</div>';
return $return;
}
echo main_menu($menu);
You don't need $menu[$key] just use the $value.
Should you not just be using $value inside your loop? And passing the entire array rather than one item of the $menu array?
$menu = array(
0 =>'top',
1 =>'photography',
2 =>'about'
);
<?php
function main_menu ($menu) {
$return = '<div class="menu_entry">' . PHP_EOL .'';
foreach( $menu as $key => $value)
{
$return .= '<a class="menu" href="index.php#' . $value . '">' . $value . '</a>' . PHP_EOL .'';
}
$return .= '</div>';
return $return;
}
?>
<?php echo main_menu($menu); ?>
Try:
echo main_menu($menu); // You will get your links printed
Instead of
echo main_menu($menu[1]); // In this case error is occured like : **Invalid argument supplied for foreach**
NOTE: You can use $value instead of $menu[$key]

mssql_fetch_array only displays one row if columns are put into variables

I'm still a PHP noob, so I apologize if this is something simple.
I am creating a fairly basic search facility for a website using PHP and mySQL. I have connected to the database, selected the database, queried the table and have fetched the table columns;
$k = htmlspecialchars($_GET['k']); // Get search query
$select = mssql_query("SELECT * FROM search WHERE Title Like '%" . $k . "%'");
if( mssql_num_rows($select) < 1) {
$noResults = 'No results found for <b>' . $k . '</b>, <label for="k">Please try again.</label>';
} else {
while ($results = mssql_fetch_array($select)) {
$title = $results['Title'];
$link = $results['Link'];
$description = $results['Description'];
}
}
When I put the $results[''] columns into variables and then try to echo out each variable like so;
if( isset($noResults)) {
echo $noResults;
} else {
echo '<li>' . '<h2>' . '' . $title . '' . '</h2>' . '<p>' . $link . '</p>' . '<p>' . $description . '</p>' . '</li>';
}
it only echo's out one row matching that query however, If I was to just simple echo out the columns like so;
echo $results['Title'];
echo $results['Link'];
echo $results['Description'];
all rows matching the query will be displayed..
I'm not sure why this is happening. If someone could help me out that would be great!
You need to use a loop:
$k = mysql_real_escape_string($_GET['k']); // Get search query
$select = mssql_query("SELECT * FROM search WHERE Title Like '%" . $k . "%'");
if( mssql_num_rows($select) < 1) {
$noResults = 'No results found for <b>' . $k . '</b>, <label for="k">Please try again.</label>';
} else {
$results= array();
while ($result = mssql_fetch_array($select)) {
$results[]= $result;
}
}
if( isset($noResults)) {
echo $noResults;
} else {
echo "<ul>";
foreach($results as $result){
echo '<li>' . '<h2>' . '' . $result['title'] . '' . '</h2>' . '<p>' . $result['link'] . '</p>' . '<p>' . $result['description'] . '</p>' . '</li>';
}
echo "</ul>";
}
Do you execute the output in the while-loop?
If you execute the while-loop and call the echo after that, each resultset will overwrite the previous, and the echo will output the last resultset which was fetched.
If you call the echo in the Loop, every result set will generate "his own" output line.
If you want to hold every resultset in a variable you can use an array, which is declared in front of the loop and gets filled in the loop.
a few things are not clear from your question, but i am assuming that you are echo'ing the variables outside the loop since you are checking isset($noResults). that means you are reassigning the variables with new values in each loop of while. so ultimately you get the last one assigned to the variables. you have to either use an array to hold the values or echo it with in the loop.

Need to add second line and third delimiter on php explode

This is tailing off my other question which was successfully answered: stackoverflow.com/questions/8597929/need-to-create-li-with-list-of-different-links-using-php-explode-method
so now I have this:
<?php
$separator1 = "\n";
$separator2 = ":";
$textarea = get_custom_field('my_custom_output');
$array = explode($separator1,$textarea);
$output = ''; // initialize the variable
foreach ($array as $item) {
list($item_text, $item_links) = explode($separator2, trim($item));
$output .= '<li class="link-class"><a title="' . $item_text . '" href="http://mywebsite.com/' . $item_links . '">' . $item_text . '</a></li>';
}
?>
<ul>
<?php print $output; ?>
</ul>
and that, using the following in a textarea which is defined to "my_custom_output":
text1:text1-page-url
text2:new-text2-page
text3:different-page-text3
and the result is
text1
text2
text3
which are successfully linked and styled. (i didnt make them links because stackoverflow doesn't let me post more than two links because i only have 3 rep).
So my next and final desired task is to do this:
text1
description 1
text2
description 2
text3
description 3
where the text1 etc are linked like before but the descriptions are not linked.
So I will do my best, right here in stackoverflow, to try it. However, I expect I will need some help. Let's go:
<?php
$separator1 = "\n";
$separator2 = ":";
$separator3 = ";";
$textarea = get_custom_field('my_custom_output');
$array = explode($separator1,$textarea);
$output = ''; // initialize the variable
foreach ($array as $item) {
list($item_text, $item_links) = explode($separator2, trim($item));
$output .= '<li class="link-class"><a title="' . $item_text . '" href="http://mywebsite.com/' . $item_links . '">' . $item_text . '</a><br /><span class="desc-class">' . $item_desc . '</span></li>';
}
?>
<ul>
<?php print $output; ?>
</ul>
and to use the following in the textarea which is is defined to "my_custom_output":
text1:text1-page-url;Text1 Description
text2:new-text2-page;Description For Text2
text3:different-page-text3;A Text3 Description
and I need the output to be:
text1
Text1 Description
text2
Description For Text2
..etc
I don't know if semicolon will work, but I can't use a space (\s) because there are spaces in the description. I am open to suggestions.
====================================================
MY NEWEST TRY:
<?php
$separator1 = "\n";
$separator2 = ":";
$separator3 = ";";
$textarea = get_custom_field('my_custom_output');
$array = explode($separator1,$textarea);
$output = ''; // initialize the variable
foreach ($array as $item) {
$itemarray = explode($separator2, trim($item));
$item_text = $itemarray[0];
list($item_links, $item_desc) = explode($separator3,$itemarray[1]);
$output .= '<li class="link-class"><a title="' . $item_text . '" href="http://mywebsite.com/' . $item_links . '">' . $item_text . '</a><br /><span class="desc-class">' . $item_desc . '</span></li>';
}
?>
<ul>
<?php print $output; ?>
</ul>
IT WORKS!!! =D
Not sure if I understand this well enough (I'm not sure what get_custom_field() gets you - can't find that as a regular PHP function), but when you explode an item that has multiple instances of the delimiter, you'll get multiple arrays.
So:
$textarea = "text1:text1-page-url;Text1 Description";
$data = explode(':',$textarea);
// at this point $data[0] will contain "text1", while $data[1] contains text1-page-url;Text1 Description"
$descarray = explode(';',$data[1]);
// then $descarray[0] contains "text1-page-url" and $descarray[1] contains "Text1 Description" so you can echo this out however you like.
To work with your code..
Assume each $item is each row at this point, like this:
$item = "text1:text1-page-url;Text1 Description";
Then this will do the trick:
foreach ($array as $item) {
$itemarray = explode($separator2, trim($item));
$item_text = $itemarray[0];
list($item_links, $item_desc) = explode(';',$itemarray[1]);
$output .= '<li class="link-class"><a title="' . $item_text . '" href="http://mywebsite.com/' . $item_links . '">' . $item_text . '</a><br /><span class="desc-class">' . $item_desc . '</span></li>';
}
I'd slightly optimize the algorithm as there is no need for second explode(). Just separate substrings within one row with the same separators (and don't forget to escape that separator inside all your data):
<?php
$row_separator = "\n";
$line_separator = ":";
$textarea = get_custom_field('my_custom_output');
$array = explode($row_separator, $textarea);
$output = ''; // initialize the variable
foreach ($array as $item) {
list($item_text, $item_links, $item_desc) = explode($line_separator, trim($item));
$output .= '<li class="link-class"><a title="' . $item_text . '" href="http://mywebsite.com/' . $item_links . '">' . $item_text . '</a><br /><span class="desc-class">' . $item_desc . '</span></li>';
}
?>
<ul>
<?php print $output; ?>
</ul>
And here is the data format I suggest to use (separate all fields by :)
text1:text1-page-url:Text1 Description
text2:new-text2-page:Description For Text2
text3:different-page-text3:A Text3 Description

Categories