Looping through 2 different arrays to check if a value exists - php

Ok well i have this array that consists of 3 arrays of objects so its looks like
$invoice
$invoice->foo
$invoice->foo->bars
$invoice->bars
$invoice->foobars
i have all the foo bars displayed in a table like
<?php foreach($invoice->foo->bars as $bar) { ?>
<tr>
<td>
<?php echo $bar->some_field;
</td>
<td>
<?php echo $bar->another_field;
</td>
</tr>
and i have a dropdown button at that looks like
<ul>
<li>edit</li>
<li>Delete</li>
<li>Add foobar</li>
</ul>
Would i am currently checking to see if the bar has a foobar by doing this
for ($i=0; $i < count($invoice->foobars); $i++) {
$foobar_bars[] = $invoice->foobars[$i]->foobar_bar_id;
}
and inside the $invoice->foo->bars loop i check to show the button like
<ul>
<li>edit</li>
<li>Delete</li>
<?php if(!in_array($bar->dd_id, $companion_bars)){ ?>
<li>Add Foobar</li>
<?php } ?>
</ul>
I was wondering if this is the most efficient way to do this or is their better ways to check whether the bar has a foobar

I think the most efficient way would be to actually have a method that tells you whether or not this is the case:
if ($bar->hasCompanionBar()) {
// the condition is TRUE
}
That way you can defer the decision what is most efficient to later. That will allow you to create the most efficient code over the lifetime of the codebase.

Related

Add additional queries to url by link

I have a site that uses query strings to retrieve the data like so:
<div id="menu-sort-dropdown" class="search-filter-item">
<p><?php echo $query_sort_title; ?></p>
<ul class="dropdown-menu">
<li>Newest</li>
<li>Oldest</li>
<li>Alphabetically</li>
</ul>
</div>
<div id="menu-category-dropdown" class="search-filter-item">
<p><?php echo $query_category_title; ?></p>
<ul class="dropdown-menu">
<li>All</li>
<li>Coaching</li>
<li>Conversation</li>
<li>Craft</li>
<li>Creativity</li>
</ul>
</div>
It works great getting the data like:
teachings/?sort=SORT_NAME_ASC
or
teachings/?category=Creativity
but I can do both like:
teachings/?category=Creativity&sort=SORT_NAME_ASC
I can't wrap my head around how to add that. If I just append the strip it will become a mess.
The following code doesn't 'duplicate' the values in the url if you keep clicking the category or sort. It's made to copy/paste and run.
// to check the values
echo '<pre>';
print_r($_GET);
echo '</pre>';
echo '<hr>';
function foo($type, $value){
$args = $_GET;
$args[$type] = $value; // prevent duplication
return http_build_query($args); // returns new query string
}
?>
SORT_DATE_LIT_ASC
<br>
SORT_NAME_ASC
<br>
Coaching
<br>
Conversation
You can also have a code to remove any of those. Add it right after the previous code (also copy/paste). Take a look:
<?php
function bar($type){
$args = $_GET;
unset($args[$type]);
return http_build_query($args); // returns new query string
}
?>
<hr>
Remove SORT
<br>
Remove CATEGORY
As for now your dropdown element do a simple action - go to provided url. If you want to select a few values then your elements should store selected value instead of open url. You can do this with for example this JS code
var menus = [];
function addElement(type, element) {
menus[type] = element;
}
The type above is number index of your menu type. For example 0 can be for sort and 1 for category - this is for ensure that you can select only one value from menu type. Now you can replace your code with something like this
<div id="menu-sort-dropdown" class="search-filter-item">
<p><?php echo $query_sort_title; ?></p>
<ul class="dropdown-menu">
<li>Newest</li>
<li>Oldest</li>
<li>Alphabetically</li>
</ul>
</div>
<div id="menu-category-dropdown" class="search-filter-item">
<p><?php echo $query_category_title; ?></p>
<ul class="dropdown-menu">
<li>All</li>
<li>Coaching</li>
<li>Conversation</li>
<li>Craft</li>
<li>Creativity</li>
</ul>
</div>
To go to the prepared URL you need to add another element like for example a button (or something else with calling openUrl function after mouse click)
<input type="button" onclick="openUrl('?')" value="Go to URL">
And the JS code for openUrl function
function openUrl(prefix) {
var url = prefix + menus.join('&');
document.location.href = url;
}

Repeating an HTML element with incrementing variables

I currently have a simple html list. What I want is to repeat this list item with each repeated element having a variable that will increase by one, each time it is repeated.
The php calls that i have included in the above list item is from the Advanced Custom Field plugin on WordPress. The variable I want to change is the number inside of those php calls.
<ul>
<li>
<?php the_field('vendor_1_name'); ?> <!--the number is the variable that i want to increase by one with each repition-->
<a href="http://<?php the_field('vendor_1_url'); ?>" target="_blank"/>
<?php the_field('vendor_1_url'); ?>
</a>
</li>
</ul>
I have an idea of how to do this using an array, but I would love to hear other methods on how to do something like this. Thanks!
<ul>
<?php for ($z = 0; $z < $n; $z++) : ?>
<li>
<?php the_field('vendor_'.$z.'_name'); ?>
<a href="http://<?php the_field('vendor_'.$z.'_url'); ?>" target="_blank">
<?php the_field('vendor_'.$z.'_url'); ?>
</a>
</li>
<?php endfor; ?>
</ul>
Where $n is the number of times it should iterate.
Use a for loop. If you have an array of items (are you grabbing vendors from a database?), just iterate through the array:
<?php
// fetch values and define $vendors
// using sql is highly recommended
echo "<ul>\n";
for ($i = 0; $i < count($vendors); $i++) {
echo "<li><a href='".$vendors[$i]['vendor_url']."'>".$vendors[$i]['vendor_name']."</a></li>\n";
}
echo "</ul>\n";
?>
Note that the array would say vendor_name instead of vendor_1_name because the field is not going to have the iteration in its name.

Using php to add classes to looped data in WP e-commerce

In WP e-commerce, I have the following in my products page template:
<ul id="product-categories">
<?php $counter = 1; ?>
<?php wpsc_start_category_query(array('category_group'=>get_option('wpsc_default_category'), 'show_thumbnails'=> get_option('show_category_thumbnails'))); ?>
<li class="four columns<?php if ($counter % 4 == 1){echo ' alpha';}else if ($counter % 4 == 0){echo ' omega';} ?>">
<?php $counter++ ; ?>
<a title="<?php wpsc_print_category_name(); ?>" href="<?php wpsc_print_category_url();?>">
<?php wpsc_print_category_image('auto', 'auto'); ?>
<span><?php wpsc_print_category_name(); ?></span>
</a>
</li>
<p><?php echo $counter ?></p>
<?php wpsc_end_category_query(); ?>
</ul>
As you can see, for every 4n-3th item, I am trying to add an alpha class, and to every 4nth item, I am trying to add an omega class to my list items, such that the display works with a grid framework.
My issue is, start_wpsc_category_query does not appear to be 'looping' like a standard WP loop, as my echoed counter value remains at 2 for every item, hence no class is added.
Does anyone know how to fix this code to make the counter value increase each time, or have a better (PHP) way of addressing the problem if you've dealt with WP e-commerce before?
Another way of approaching would be to write a foreach loop for WP e-commerce categories, if anyone knows how to do this.
Thanks a million in advance.

Loop through PHP function, display userdata from Mysql - limit to display to 25 items and add next button

I have this PHP function, which I use to display my userdata. If run once it will basicly display a div with the userdata in it.
function listings($fornavn, $efternavn, $email, $adresse, $tlf, $postnr, $city, $fodselsdag, $brugerid,$bartype,$idbar)
{
?>
<div class="container">
<span class="records" id="id-<?php echo $brugerid;?>">
<div class="customer bidDiv clearfix">
<?php if ($bartype=='temp_vip') { ?>
<ul>
<li>
<span class="actionSpan" id="<?php echo $brugerid;?>" value="<?php echo $idbar;?>">
<a class="edit-opt" id="godkend" href="#">GODKEND</a>
</span>
</li>
<li>
<span class="actionSpan" id="delete-<?php echo $brugerid;?>" value="<?php echo $bartype;?>">
<a class="delete-opt" id="delete" href="#">Afvis</a>
</span>
</li>
<?php }else{ ?>
<ul>
<li>
<span class="actionSpan" id="delete-<?php echo $brugerid;?>" value="<?php echo $bartype;?>">
<a class="delete-opt" id="delete" href="#">Slet</a>
</span>
</li>
<li>
<a class="edit-opt" href="editform.php?id=<?php echo $brugerid."&bartype=".$bartype;?>" rel="facebox">Rediger</a>
</li>
<?php if ($bartype =='vip'){?>
<li>
<a class="print-opt" href="print.php?id=<?php echo $brugerid;?>" rel="facebox">Print</a>
</li>
<?php }else{
// Dont render vip link
}}?>
</ul>
<p class="contact-data">
<?php echo $email;?><br>
Tlf.: <?php echo $tlf;?>
</p>
<div class="base-data">
<h4><?php echo ucwords($fornavn)." ".ucwords($efternavn);?></h4>
<p>Fødselsdag <?php echo $fodselsdag;?></p>
<address><?php echo ucwords($adresse) ." ". $postnr ." ". ucwords($city);?></address>
</div>
</div><!-- end customer -->
</div>
</span>
<?php
I mostly use this function in a loop, to display all users from my MySQL database, who has a specific relation to something else.
This is all working great. But currently it would pull all results at once. Right now I only have 5 members, so its no problem, but say I get 800 or 2000 members, the list of users would get very long.
So I want to implement some kind of limit on how many users it displays, but still be able to browse through all the users. Many sites use something like pages and split up the results that way. Links like:
[1] [2] [3] [Last page>>]
I can't figure out how to start doing this? How would I proceed?
Also looked into this Jquery plugin:
http://andersonferminiano.com/jqueryscrollpagination/
But it keeps reloading my PHP file which results in the Loops being restarted, and it simply displays the results over and over again endlessly.
Can someone help me with the logic behind creating this? Or better, point me in a direction where I could use the jquery pluging above - where it only loads the loop one time, and renders the results as I scroll.
Any help or pointers will be greatly appreciated!
Thanks
Jquery pagination by default will only break-up the given table into several tabs on the page, that is all the data is actually loaded. There are some that let you do an AJAX request to fetch the next page, to work in conjunction with your PHP code.
Ideally, you want to limit the query using LIMIT (number of rows in the result object) and OFFSET (Start from row X ) which will give you number of records starting from your offset row up until the limit, and then use logic on the PHP side to determine the maximum number of pages.
$page = $_POST["page"] * 25; // make sure that page 0 is the starting page or calculate
$SQL = "SomeQueryText LIMIT 25 OFFSET '$page'" ;
$result = query ($SQL);

zebra (even/odd) rows css in <ul> and hyperlink issue

I have this little select code which should provide a 'zebra' even/odd rows. I don't understand how to change the css for that:
1, every other that will be listed (and not every second) should have .even css
2, if one of them clicked should be bold as well
(I could not figure out, how to merge these two issue)
Any help would be appreciated, from a beginner.
<div id="left">
<?php
$query = $pdo->prepare('SELECT id, name FROM test1 ORDER BY name ASC');
$query->execute();
?>
<ul>
<?php foreach ($query as $i => $row) { ?>
<li>
<?php if ($i)?>
<input name="checkbox_add[]" id="test_<?php echo $i ?>" type="checkbox" value="<? echo $row['id']; ?>"/>
<label for="test_<?php echo $i ?>"><?php echo $row['name']; ?></label>
</li>
<?php } ?>
</ul>
</div>
You should define a class odd or even (depends on which one you would like to have in alternating color) in your CSS.
Let's say you chose 'odd'. Then define a counter in your PHP code and check whether the remainder modulo 2 is equal to 1 -> if so add class 'odd' to the <li>.
<div id="left">
<?php
$query = $pdo->prepare('SELECT id, name FROM test1 ORDER BY name ASC');
$query->execute();
$idx = 0;
?>
<?php if ($idx % 2 == 0): ?>
<li>
<?php else: ?>
<li class="odd">
<?php endif; ?>
<?php
$idx++;
if ($i): ?>
...your <input> and <label>...
However, bolding the corresponding row on clicking it is something that you would preferrably do in Javascript, as it is a client-side event, the code responding to that belongs on the client side, too. Here is a crude solution, just to show what I mean, but it is not recommended with respect to clean separation of concerns and "unobtrusive" Javascript. Ideally you would put this in a separate Javascript file that attaches the event handler form within Javascript, this doesn't belong in the HTML if you want to keep it clean.
<input type="checkbox" onclick="this.parentNode.className='bold'" ...>
It would be easier to do it with jquery or prototype or something similar. I would do it with prototype, something like this:
$$('ul li:nth-child(odd)').invoke('addClassName', 'alt-row');
// Add class "alt-row" to even table rows
So, select all odd numbered li items, and apply proper css for it (invoke). You do the same thing with the odd list items, just apply other css
And for the bold part, simply add onClick event for every li item, and set style that will bold it, something like this:
<li onClick="this.className='bold'">Something</li>

Categories