PHP - Show Last Part Of Array, Same Order, No Duplicates
I wish to get only the last part of each array 'g'
And then show non duplicated 'g' but in the same order that it was in the original array. Code: [Select] <?php $formarray = array( 'name' => array( 'i1'=> array('a'=>'a1', 'b'=>'b1', 'c'=>'c1', 'd'=>'d1', 'e'=>'e1', 'f'=>'f1', 'g'=>'g1'), 'i2'=> array('a'=>'a2', 'b'=>'b2', 'c'=>'c2', 'd'=>'d2', 'e'=>'e2', 'f'=>'f2', 'g'=>'g2'), 'i3'=> array('a'=>'a3', 'b'=>'b3', 'c'=>'c3', 'd'=>'d3', 'e'=>'e3', 'f'=>'f3', 'g'=>'g3'), 'i4'=> array('a'=>'a4', 'b'=>'b4', 'c'=>'c4', 'd'=>'d4', 'e'=>'e4', 'f'=>'f4', 'g'=>'g4'), ) ); foreach ($formarray as $newarray => $a) { ?><strong><?=$newarray;?></strong><br><? foreach ($a as $key => $k) { ?>"<?=$key;?>", <? foreach ($k as $b) { //if ($k['DBfield'] != "") { ?>"<?=$b;?>", <? //} } ?><br><? } //end of second foreach ?><br><br><br><? } //end of first foreach ?> Similar Tutorialsthe interface explains everything Code: [Select] #page1.html <html> <head> </head> <body> <table border='0' width='50%' cellspacing='0' cellpadding='0' > <form name=form1 method=post action="page2.php"> <?PHP $postData[] = array(); $postData[0] = '9'; $postData[1] = '8'; $postData[2] = '7'; $postData[3] = '6'; ?> <tr> <td><b>Choose your order</b></td> <td> </td> <td> <input type=checkbox name=scripts[] value='<?PHP $postData[0]; ?>'>pasta <br> <input type=checkbox name=scripts[] value='<?PHP $postData[1]; ?>'>burger <br> <input type=checkbox name=scripts[] value='<?PHP $postData[2]; ?>'>fries <br> <input type=checkbox name=scripts[] value='<?PHP $postData[3]; ?>'>chili dog <br> <br> </td> </tr> <tr><td align=center > <input type=submit value=Submit> <input type=reset value=Reset></td></tr> </form> </table> </body> </html> Code: [Select] #page2.php <?PHP if ($_SERVER['REQUEST_METHOD'] == 'POST') { if (isset($_POST['scripts'])) { $cb = $_POST['scripts']; $numRows = count($cb); print "you have chosen the following order numbers:"; for($i=0; $i<$numRows; $i++){ print $cb[$i] . "<br>"; } } else{ print "you have'nt checked anything!"; } } ?> What do? My query gets the results and orders by one of the fields. Once I get the MySQL results I would like to find the first entry that has a letter as the first character of the same field that the list was ordered by, then split the results in to two parts and swap them. So that the results that have a letter at the start of the same sorted field are as the begining and the results that have the numbers as the start at the end of the array. But also so that the array works the same way as the original results string, so i can use say $results['mysqlfield'] Quote Hi guys im trying to get rid of records with duplicate phone numbers here's my array Code: [Select] Array ( [0] => Array ( [0] => 11-1-89677-362123164 [1] => 11 [2] => testadmin [3] => 61415676836 [4] => 2011-11-16 [5] => 1 [6] => 0 [7] => 0 [8] => [9] => 0 [10] => 0 [11] => 0 ) [1] => Array ( [0] => 11-1-89688-362186603 [1] => 11 [2] => testadmin [3] => 61415556677 [4] => 2011-08-12 [5] => 0 [6] => 0 [7] => 0 [8] => [9] => 0 [10] => 0 [11] => 0 ) [2] => Array ( [0] => 11-1-89689-362186773 [1] => 11 [2] => testadmin [3] => 61415676836 [4] => 2011-08-12 [5] => 0 [6] => 0 [7] => 0 [8] => [9] => 0 [10] => 0 [11] => 0 ) [3] => Array ( [0] => 11-1-89690-362186926 [1] => 11 [2] => testadmin [3] => 61415223344 [4] => 2011-08-12 [5] => 0 [6] => 0 [7] => 0 [8] => [9] => 0 [10] => 0 [11] => 0 ) ) Quote I can't quit figure this out any sujestions would be gold,,, this is my attempt but its not working Code: [Select] $final = array(); foreach ($phoneNumberArray as $array[3]) { if(!in_array($array, $final)){ $final[] = $array; } } print_r($final); Hi I have an array from an sql query and i would like to eliminates all the duplicates, i have google search for an answer without success, any help would be aprecciated $result = $stmt->fetchAll(PDO::FETCH_ASSOC); $final = array(); $json = array(); if ($idCoord > 0 || $isDirecao > 0) { foreach ($result as $row) { $idAtividade = $row['idAtividade']; if (!isset($final[$idAtividade])) { $final[$idAtividade]['Escola'] = $row['Escola']; $final[$idAtividade]['Atividade'] = $row['Atividade']; $final[$idAtividade]['Periodo'] = $row['Periodo']; $final[$idAtividade]['Mes'] = $row['Mes']; $final[$idAtividade]['haveClasses'] = $row['haveClasses']; $final[$idAtividade]['DataPrevista'] = $row['DataPrevista']; $final[$idAtividade]['Destinatarios'] = $row['Destinatarios']; $final[$idAtividade]['Orcamento'] = $row['Orcamento']; $final[$idAtividade]['Organizador'] = $row['Organizador']; $final[$idAtividade]['Obs'] = $row['Obs']; $final[$idAtividade]['PdfAtividade'] = $row['PdfAtividade']; $final[$idAtividade]['Avaliacao'] = $row['Avaliacao']; $final[$idAtividade]['idProfessor'] = $row['idProfessor']; $final[$idAtividade]['PdfAvaliacao'] = $row['PdfAvaliacao']; $final[$idAtividade]['Validado'] = $row['Validado']; $final[$idAtividade]['Nome'] = array(); $final[$idAtividade]['Grupo'] = array(); $final[$idAtividade]['Departamento'] = array(); } $final[$idAtividade]['Nome'][] = $row['Nome']; $final[$idAtividade]['Grupo'][] = $row['Grupo']; $final[$idAtividade]['Departamento'][] = $row['Departamento']; } foreach ($final as $idVisita => $reservation) { $json[] = $reservation; } } echo json_encode($json); } And this is an example i'm receiving
So you can see that Grupo has 4 times the value "500" and Departamento has 4 times that string... How can avoid this and have only one value of each?
Thanks
Hi All, I've a loop which creates an array as follows: $product_table[] = ['SKU' => $sku, 'Label' => $attribute_name, 'Value' => $term_obj->name ]; I'm then grouping the data by SKU code: #group the products by SKU $group_products = array(); foreach ($product_table as $element) : $group_products[$element['SKU']][] = $element; endforeach; Finally, I output the data: #output the data foreach ($group_products as $itemName => $rows) : echo '<tr>'; #echo '<td>', $element['SKU'], '</td>'; $i=0; foreach ($rows as $row) : $i++; #echo '<td>'. $row["SKU"]. '</td><td>'. $row["Label"]. '</td><td>'. $row["Value"]. '</td>'; if ($i == 1): echo '<td>'. $row["SKU"]. '</td><td>'. $row["Value"]. '</td>'; else: echo '<td>'. $row["Value"]. '</td>'; endif; #echo '<td>'. $row["Value"]. '</td>'; endforeach; echo '</tr>'; endforeach; ?> And looks like: Product code System Pack Quantity XT1CWH System 1 1 x 3m XT2CWH System 2 1 x 3m XT3CWH System 3 1 x 3m
This works perfectly fine. However, some products share the same SKU and therefore it causes an issue, like the below: Product code System Pack Quantity XT1CLWH System 1 8 x 3m System 2 8 x 3m System 3 8 x 3m Is there a way I can avoid this, so if perhaps creates the new row but shows the same SKU code? Many thanks Hi guys! i got this code: Code: [Select] <? $x = "abcde"; str_split($x); for ($k=0; $k<=119; $k++){ $ax = array($x[0],$x[1],$x[2],$x[3],$x[4]); shuffle($ax); $text = implode("", $ax) . ""; echo $text; echo "<br />"; } ?> if you test it you see that it is working but giving me allot of duplicates results! there is a way to ignore duplicaes while it is runing? thanx. So Im building this little link scraper. The problem I am having is when it outputs the links that are in the array its got duplicate elements. I'm trying to erase the dupes and only show unique values. I've tryed array_unique() with out success as well as in_array(). Any help would be appreciated! //PAGE WE ARE GETTING LINKS ON $diags = str_get_html(getDiagramLinks($html)); //GET THE DIAGRAM LINKS TO PAGES INTO ARRAY foreach($diags->find('a') as $f) { $diagLinks[] = $f->href; } //iterate through the array for($i=0; $i<sizeof($diagLinks); $i++) { //ignore if blank element if(trim($diagLinks[$i]) !== ' ') { echo $diagLinks[$i]. '<br>'; } } The Output: Code: [Select] /partsearch/model.aspx?diagram_id=110375 /partsearch/model.aspx?diagram_id=110375 /partsearch/model.aspx?diagram_id=110376 /partsearch/model.aspx?diagram_id=110376 /partsearch/model.aspx?diagram_id=110377 /partsearch/model.aspx?diagram_id=110377 /partsearch/model.aspx?diagram_id=110378 /partsearch/model.aspx?diagram_id=110378 /partsearch/model.aspx?diagram_id=110379 /partsearch/model.aspx?diagram_id=110379 /partsearch/model.aspx?diagram_id=110380 /partsearch/model.aspx?diagram_id=110380 Hi, got a problem with my arrays, every string gets duplicated 11 times instead of just one time. How to fix this? Hello I have a while loop which outputs countrys from the database (im making a "filter by" function). For example, the loop outputs: Denmark Belgium Holland Brazil Japan Brazil Denmark I want to sort these alphabetically and then remove duplicates... Can somebody explain to me how? I don't know how to get them into an array to do it... Doing an API call and want to remove duplicates so I can display the products by brand. Problem I am having now is when I try to display the brands, I am getting duplicate brands. When I display the brands I am getting Nike, Nike, Reebook. When I just want, Nike, Reebok. My Code Code: [Select] <?php $results = array(); //array from API call $results2 = $results['data']; function multi_unique($array) { foreach ($array as $k=>$na) $new[$k] = serialize($na); $uniq = array_unique($new); foreach($uniq as $k=>$ser) $new1[$k] = unserialize($ser); return ($new1); } $results3 = multi_unique($results2); foreach ($results3 as $var) { echo $var['brand']; ?> <br /> <?php } ?> The array Code: [Select] { "errors": [ ], "warnings": [ ], "data": [ { "url": "http://[...]", "image_url": "[...]", "image_thumb_url": "[...]", "keyword": "Red Running Shoes", "description": "Red Running Shoes - Perfect for long jogs!", "category": "Shoes", "price": "59.99", "price_sale": null, "currency": "USD", "merchant": "", "brand": "Nike", "upc": "0944588778", "isbn": null, "sales": 23 }, { "url": "http://[...]", "image_url": "http://[...]", "image_thumb_url": null, "keyword": "Blue Running Shoes", "description": "Blue Running Shoes - Perfect for long jogs!", "category": "Shoes", "price": "59.99", "price_sale": "49.99", "currency": "USD", "merchant": "", "brand": "Nike", "upc": "0944588779", "isbn": null, "sales": 12 } { "url": "http://[...]", "image_url": "http://[...]", "image_thumb_url": null, "keyword": "Black Running Shoes", "description": "Black Running Shoes - Perfect for long jogs!", "category": "Shoes", "price": "59.99", "price_sale": "49.99", "currency": "USD", "merchant": "", "brand": "Reebok", "upc": "0944554779", "isbn": null, "sales": 12 } ], "coupons": [ ], "countryCode": "US", "page": 1, "limit": 10, "totalRecords": 3 } I'm working on a simple ad server and would like to display the ads in order (not random). I'm fairly certain I can do something like this: Code: [Select] // Get the last ad id, or becomes 0 if not available $lastid = ($_GET['lastid'] == '') ? '0' : $_GET['lastid']; // Get the next ad in order, or get the first one available mysql_query("SELECT adcode FROM ads WHERE zone='$zoneid' AND id > $lastid ORDER BY id ASC LIMIT 1"); The above code would get the first ad or the next ad in order.. How do I go back to the beginning when I run out of ads to show? Hello, my name is Casper. Hello all, I need to make a rotating banner system for a client. They want about 5 banners to rotate with Javascript. However they want the visitor to sort of step through each one on each refresh. So if I have 5 banners and I go to the site, I see banner 1 and then the javascript rotates through each one. When I go back to the site, they want it to start with banner 2 and then the javascript will rotate through each one. Then on and on. Go back and see banner 3, then step through again. I have a nice Javascript image slider I'd like to use. It basically just requires the images in order. Like: <img src="1.jpg"/> <img src="2.jpg"/> <img src="3.jpg"/> <img src="4.jpg"/> <img src="5.jpg"/> I've thought about it and I think the best way to do this would just be using PHP and a cookie. So when the viewer first goes to the site, PHP checks for the cookie. If it exists, it pulls the starting image #. If it doesn't, it starts at 0 and sets the cookie. As for the images part, I figured an associate array would work well. The key would be what the cookie logic is based on, and then the image HTML would be in the array. So you visit the site without a cookie it would be... 0 => <img src="1.jpg"/> 1 => <img src="2.jpg"/> 2 => <img src="3.jpg"/> 3 => <img src="4.jpg"/> 4 => <img src="5.jpg"/> Then when you go back to the site, I need the array to be re-ordered like this: 0 => <img src="2.jpg"/> 1 => <img src="3.jpg"/> 2 => <img src="4.jpg"/> 3 => <img src="5.jpg"/> 4 => <img src="1.jpg"/> What's the best way to go about this array logic? My experience with manipulating data inside arrays is rather limited. Basically I need it to say "Start with key # and then reorder array based on that" Hi all, I have the following : Code: [Select] print_r($fqlResult); Which gives the following result : Code: [Select] Array ( [0] => Array ( [src_big] => http://a5.sphotos.ak.fbcdn.net/hphotos-ak-ash4/299117_2121699756933_1079004376_2442101_3103384_n.jpg ) ) I want to grab just the image url from it and store it in a seperate variable. Any ideas how I can do this plzzz ? Thanks in advance, Scott. So, I am making a system that shows if there are new posts or not. How I have it done is a singular array called "Read" will have all of the IDs of the read posts. It is entered in the database like so: $ID2= $_SESSION['UserID']; $ID2 = mysql_real_escape_string($ID2); $Readornot=mysql_query("SELECT * FROM forum_read WHERE Reader_ID='$ID2'"); $Readornot2=mysql_fetch_array($Readornot); if($ID2==0) { } else { if(empty($Readornot2)) { $Read1= array("Read" => $Get_TopicID); $Read2 = implode('-',$Read1); mysql_query("INSERT INTO forum_read (Reader_ID,`Read`) values ('$ID2','$Read2')") or die(mysql_error()); } else { $cr_topicid=$Readornot2['Read']; if(strpos($cr_topicid,'-')) { $cr_topicid=explode('-',$cr_topicid); if(!in_array($Get_TopicID,$cr_topicid,true)) { $Read0=implode('-',$cr_topicid); $Read1= array("Read" => $Read0, $Get_TopicID); $Read2= implode('-',$Read1); mysql_query("UPDATE forum_read SET`Read`='$Read2' WHERE Reader_ID='$ID2'") or die(mysql_error()); } } else { if($cr_topicid==$Get_TopicID) { } else { $Read1= array("Read" => $cr_topicid, $Get_TopicID); $Read2= implode('-',$Read1); mysql_query("UPDATE forum_read SET`Read`='$Read2' WHERE Reader_ID='$ID2'") or die(mysql_error()); } } } } It all works fine and dandy to the point where if it's in the database an icon will be black and white, and if its not it wont, signifying read or unread. What I need to do, however, is make it so when there is a new post, it takes all of the entries in the database with the topic ID out of the database, and strips the one part. What I thought of at first was to use str_replace to replace "-" . $TopicID . "-" with "-" But of course, that won't work, because the very first entry could be the topic ID, so it would just be $TopicID- and not -$TopicID- in the database. So, how would I go about doing this? Hi,
In reference to my first attached image, I have a form which displays two SELECT/drop-down fields (labeled "Store Name" and "Item Description".....and both of which pull-in values from two separate lookup/master tables, in addition to providing an additional option each for "NEW STORE" and "NEW ITEM").
Now, when first-run, and/or if "NEW STORE" and "NEW ITEM" are not selected from the drop-down's then the two fields in green ("New Store Name" and "New Item Name" are hidden, by means of the following code:
<div class="new-store-container" id="new-store-container" name="new-store-container" style="display:none;"> <div class="control-group"> <div class="other-store" id="new_store_name"> <?php echo standardInputField('New Store Name', 'new_store_name', '', $errors); ?> </div> </div> </div>Conversely, if "NEW STORE" and/or "NEW ITEM" are selected from the two drop-down's then one (or both) of the "New Name" fields are unhidden by means of the following two pieces of code, one PHP and the second JS: <select class="store-name" name="store_id" id="store_id" onclick="toggle_visibility('store_id','new-store-container')"> <?php echo $store_options; ?> <?php if($values['store_id'] == "OTH") { echo "<option value='OTH' selected> <<<--- NEW STORE --->>> </option>"; } else { echo '<OPTION VALUE="OTH"> <<<--- NEW STORE --->>> </OPTION>'; } ?> </select> function toggle_visibility(fieldName, containerName) { var e = document.getElementById(fieldName); var g = document.getElementById(containerName); if (e.value == 'OTH') { if(g.style.display == 'none') g.style.display = 'block'; else g.style.display = 'none'; } }All of that is working just fine. The problem I'm having is that when I click the "Create" button, after having left any one of the form fields blank, the two "New Name" fields are hidden again, which I don't want to happen i.e. I want them to remain visible (since the values of "store_id" and/or "item_id" are "OTH"), so that the user can enter values into one or both of them, without havng to click on the drop-down a second time in order to execute the "on-click" code. The second attached image shows how the fields are hidden, after clicking "Create". How can I achieve that? It would be greate if someone could cobble-up the required code and provide it to me, since I'm relatively new to this. Thanks much. Snap1.png 26.14KB 0 downloads Snap2.png 149.47KB 0 downloads I have an array like this
$rows = array( array( 'fruit.name' => 'Apple', 'fruit.colour' => 'Red', 'fruit.weight' => '0.1', 'vegetable.name' => 'Carrot', 'vegetable.colour' => 'Orange', 'vegetable.weight' => '0.05' ), array( 'fruit.name' => 'Banana', 'fruit.colour' => 'Yellow', 'fruit.weight' => '0.7', 'vegetable.name' => 'Potato', 'vegetable.colour' => 'Brown', 'vegetable.weight' => '0.6' ) ); I'm using a woocommerce order report plugin, some customers order multiple products but order report shows only number of order and one product name: I want to see all product names: also I want to see customer notes it doesn't show up
<?php /** * Plugin Name: Custom Order Report * Description: Generates a report on individual WooCommerce products sold during a specified time period. * Version: 1.4.8 */ // Add the Product Sales Report to the WordPress admin add_action('admin_menu', 'hm_psrf_admin_menu'); function hm_psrf_admin_menu() { add_submenu_page('woocommerce', 'Custom Order Report', 'Custom Order Report', 'view_woocommerce_reports', 'hm_sbpf', 'hm_sbpf_page'); } function hm_psrf_default_report_settings() { return array( 'report_time' => '30d', 'report_start' => date('Y-m-d', current_time('timestamp') - (86400 * 31)), 'report_end' => date('Y-m-d', current_time('timestamp') - 86400), 'order_statuses' => array('wc-processing', 'wc-on-hold', 'wc-completed'), 'products' => 'all', 'product_cats' => array(), 'product_ids' => '', 'variations' => 0, 'orderby' => 'quantity', 'orderdir' => 'desc', 'fields' => array('product_id', 'product_sku', 'product_name', 'quantity_sold', 'gross_sales'), 'limit_on' => 0, 'limit' => 10, 'include_header' => 1, 'exclude_free' => 0 ); } // This function generates the Product Sales Report page HTML function hm_sbpf_page() { $savedReportSettings = get_option('hm_psr_report_settings'); if (isset($_POST['op']) && $_POST['op'] == 'preset-del' && !empty($_POST['r']) && isset($savedReportSettings[$_POST['r']])) { unset($savedReportSettings[$_POST['r']]); update_option('hm_psr_report_settings', $savedReportSettings); $_POST['r'] = 0; echo('<script type="text/javascript">location.href = location.href;</script>'); } $reportSettings = (empty($savedReportSettings) ? hm_psrf_default_report_settings() : array_merge(hm_psrf_default_report_settings(), $savedReportSettings[ isset($_POST['r']) && isset($savedReportSettings[$_POST['r']]) ? $_POST['r'] : 0 ] )); // For backwards compatibility with pre-1.4 versions if (!empty($reportSettings['cat'])) { $reportSettings['products'] = 'cats'; $reportSettings['product_cats'] = array($reportSettings['cat']); } $fieldOptions = array( 'order_id' => 'Order ID', /*'product_id' => 'Product ID',*/ 'customer_name' => 'Customer Name', /*'variation_id' => 'Variation ID',*/ 'city' => 'City', 'address' => 'Address', 'product_name' => 'Product Name', 'quantity_sold' => 'Quantity Sold', /*'product_sku' => 'Product SKU',*/ 'gross_sales' => 'Gross Sales', 'product_categories' => 'Schools', /*'variation_attributes' => 'Variation Attributes',*/ /*'gross_after_discount' => 'Gross Sales (After Discounts)'*/ 'ceremony_date' => 'Ceremony Date', 'ceremony_time' => 'Ceremony Time', ); include(dirname(__FILE__).'/admin.php'); } // Hook into WordPress init; this function performs report generation when // the admin form is submitted add_action('init', 'hm_sbpf_on_init', 9999); function hm_sbpf_on_init() { global $pagenow; // Check if we are in admin and on the report page if (!is_admin()) return; if ($pagenow == 'admin.php' && isset($_GET['page']) && $_GET['page'] == 'hm_sbpf' && !empty($_POST['hm_sbp_do_export'])) { // Verify the nonce check_admin_referer('hm_sbpf_do_export'); $newSettings = array_intersect_key($_POST, hm_psrf_default_report_settings()); foreach ($newSettings as $key => $value) if (!is_array($value)) $newSettings[$key] = htmlspecialchars($value); // Update the saved report settings $savedReportSettings = get_option('hm_psr_report_settings'); $savedReportSettings[0] = array_merge(hm_psrf_default_report_settings(), $newSettings); update_option('hm_psr_report_settings', $savedReportSettings); // Check if no fields are selected or if not downloading if (empty($_POST['fields']) || empty($_POST['hm_sbp_download'])) return; // Assemble the filename for the report download $filename = 'Product Sales - '; if (!empty($_POST['cat']) && is_numeric($_POST['cat'])) { $cat = get_term($_POST['cat'], 'product_cat'); if (!empty($cat->name)) $filename .= addslashes(html_entity_decode($cat->name)).' - '; } $filename .= date('Y-m-d', current_time('timestamp')).'.csv'; // Send headers header('Content-Type: text/csv'); header('Content-Disposition: attachment; filename="'.$filename.'"'); // Output the report header row (if applicable) and body $stdout = fopen('php://output', 'w'); if (!empty($_POST['include_header'])) hm_sbpf_export_header($stdout); hm_sbpf_export_body($stdout); exit; } } // This function outputs the report header row function hm_sbpf_export_header($dest, $return=false) { $header = array(); foreach ($_POST['fields'] as $field) { switch ($field) { case 'order_id': $header[] = 'Order ID'; break; case 'product_name': $header[] = 'Product Name'; break; case 'quantity_sold': $header[] = 'Quantity Sold'; break; case 'gross_sales': $header[] = 'Gross Sales'; break; case 'product_categories': $header[] = 'Schools'; break; case 'customer_name': $header[] = 'Customer Name'; break; case 'city': $header[] = 'City'; break; case 'address': $header[] = 'Address'; break; case 'ceremony_date': $header[] = 'Ceremony Date'; break; case 'ceremony_time': $header[] = 'Ceremony Time'; break; } } if ($return) return $header; fputcsv($dest, $header); } // This function generates and outputs the report body rows function hm_sbpf_export_body($dest, $return=false) { global $woocommerce, $wpdb; $product_ids = array(); if ($_POST['products'] == 'cats') { $cats = array(); foreach ($_POST['product_cats'] as $cat) if (is_numeric($cat)) $cats[] = $cat; $product_ids = get_objects_in_term($cats, 'product_cat'); } else if ($_POST['products'] == 'ids') { foreach (explode(',', $_POST['product_ids']) as $productId) { $productId = trim($productId); if (is_numeric($productId)) $product_ids[] = $productId; } } // Calculate report start and end dates (timestamps) switch ($_POST['report_time']) { case '0d': $end_date = strtotime('midnight', current_time('timestamp')); $start_date = $end_date; break; case '1d': $end_date = strtotime('midnight', current_time('timestamp')) - 86400; $start_date = $end_date; break; case '7d': $end_date = strtotime('midnight', current_time('timestamp')) - 86400; $start_date = $end_date - (86400 * 6); break; case '1cm': $start_date = strtotime(date('Y-m', current_time('timestamp')).'-01 midnight -1month'); $end_date = strtotime('+1month', $start_date) - 86400; break; case '0cm': $start_date = strtotime(date('Y-m', current_time('timestamp')).'-01 midnight'); $end_date = strtotime('+1month', $start_date) - 86400; break; case '+1cm': $start_date = strtotime(date('Y-m', current_time('timestamp')).'-01 midnight +1month'); $end_date = strtotime('+1month', $start_date) - 86400; break; case '+7d': $start_date = strtotime('midnight', current_time('timestamp')) + 86400; $end_date = $start_date + (86400 * 6); break; case '+30d': $start_date = strtotime('midnight', current_time('timestamp')) + 86400; $end_date = $start_date + (86400 * 29); break; case 'custom': $end_date = strtotime('midnight', strtotime($_POST['report_end'])); $start_date = strtotime('midnight', strtotime($_POST['report_start'])); break; default: // 30 days is the default $end_date = strtotime('midnight', current_time('timestamp')) - 86400; $start_date = $end_date - (86400 * 29); } // Assemble order by string $orderby = (in_array($_POST['orderby'], array('product_id', 'gross', 'gross_after_discount')) ? $_POST['orderby'] : 'quantity'); $orderby .= ' '.($_POST['orderdir'] == 'asc' ? 'ASC' : 'DESC'); // Create a new WC_Admin_Report object include_once($woocommerce->plugin_path().'/includes/admin/reports/class-wc-admin-report.php'); $wc_report = new WC_Admin_Report(); $wc_report->start_date = $start_date; $wc_report->end_date = $end_date; //echo(date('Y-m-d', $end_date)); $where_meta = array(); if ($_POST['products'] != 'all') { $where_meta[] = array( 'type' => 'order_item_meta', 'meta_key' => '_product_id', 'operator' => 'in', 'meta_value' => $product_ids ); } if (!empty($_POST['exclude_free'])) { $where_meta[] = array( 'meta_key' => '_line_total', 'meta_value' => 0, 'operator' => '!=', 'type' => 'order_item_meta' ); } // Get report data // Avoid max join size error $wpdb->query('SET SQL_BIG_SELECTS=1'); // Prevent plugins from overriding the order status filter add_filter('woocommerce_reports_order_statuses', 'hm_psrf_report_order_statuses', 9999); // Based on woocoommerce/includes/admin/reports/class-wc-report-sales-by-product.php $sold_products = $wc_report->get_order_report_data(array( 'data' => array( '_product_id' => array( 'type' => 'order_item_meta', 'order_item_type' => 'line_item', 'function' => '', 'name' => 'product_id' ), '_qty' => array( 'type' => 'order_item_meta', 'order_item_type' => 'line_item', 'function' => 'SUM', 'name' => 'quantity' ), '_line_subtotal' => array( 'type' => 'order_item_meta', 'order_item_type' => 'line_item', 'function' => 'SUM', 'name' => 'gross' ), '_line_total' => array( 'type' => 'order_item_meta', 'order_item_type' => 'line_item', 'function' => 'SUM', 'name' => 'gross_after_discount' ), /*usama*/ 'order_id' => array( 'type' => 'order_item', 'order_item_type' => 'line_item', 'function' => '', 'name' => 'order_id' ) /*usama*/ ), 'query_type' => 'get_results', 'group_by' => 'order_id', 'where_meta' => $where_meta, 'order_by' => $orderby, 'limit' => (!empty($_POST['limit_on']) && is_numeric($_POST['limit']) ? $_POST['limit'] : ''), 'filter_range' => ($_POST['report_time'] != 'all'), 'order_types' => wc_get_order_types('order_count'), 'order_status' => hm_psrf_report_order_statuses() )); // Remove report order statuses filter remove_filter('woocommerce_reports_order_statuses', 'hm_psrf_report_order_statuses', 9999); if ($return) $rows = array(); // Output report rows foreach ($sold_products as $product) { $row = array(); /*usama*/ $order = wc_get_order($product->order_id); $customerName = $order->get_billing_first_name().' '.$order->get_billing_last_name(); $billingCity = $order->get_billing_city(); $billingAddress1 = $order->get_billing_address_1(); //echo $product->order_id; //echo $customerName.$city.$billingAddress1; //echo '<pre>';print_r($order);exit; /*usama*/ foreach ($_POST['fields'] as $field) { switch ($field) { case 'order_id': $row[] = $product->order_id; break; case 'product_name': $row[] = html_entity_decode(get_the_title($product->product_id)); break; case 'quantity_sold': $row[] = $product->quantity; break; case 'gross_sales': $row[] = $product->gross; break; /*case 'variation_id': $row[] = (empty($product->variation_id) ? '' : $product->variation_id); break; case 'product_sku': $row[] = get_post_meta($product->product_id, '_sku', true); break;*/ case 'product_categories': $terms = get_the_terms($product->product_id, 'product_cat'); if (empty($terms)) { $row[] = ''; } else { $categories = array(); foreach ($terms as $term) $categories[] = $term->name; $row[] = implode(', ', $categories); } break; case 'customer_name': $row[] = $customerName; break; case 'city': $row[] = $billingCity; break; case 'address': $row[] = $billingAddress1; break; /*case 'gross_after_discount': $row[] = $product->gross_after_discount; break;*/ /*usama*/ case 'ceremony_date': $row[] = $order->get_meta( '_billing_myfield12', true ); break; case 'ceremony_time': $row[] = $order->get_meta( '_billing_myfield13', true ); break; } } if ($return) $rows[] = $row; else fputcsv($dest, $row); } if ($return) return $rows; } add_action('admin_enqueue_scripts', 'hm_psrf_admin_enqueue_scripts'); function hm_psrf_admin_enqueue_scripts() { wp_enqueue_style('hm_psrf_admin_style', plugins_url('css/hm-product-sales-report.css', __FILE__)); wp_enqueue_style('pikaday', plugins_url('css/pikaday.css', __FILE__)); wp_enqueue_script('moment', plugins_url('js/moment.min.js', __FILE__)); wp_enqueue_script('pikaday', plugins_url('js/pikaday.js', __FILE__)); } // Schedulable email report hook add_filter('pp_wc_get_schedulable_email_reports', 'hm_psrf_add_schedulable_email_reports'); function hm_psrf_add_schedulable_email_reports($reports) { $reports['hm_psr'] = array( 'name' => 'Product Sales Report', 'callback' => 'hm_psrf_run_scheduled_report', 'reports' => array( 'last' => 'Last used settings' ) ); return $reports; } function hm_psrf_run_scheduled_report($reportId, $start, $end, $args=array(), $output=false) { $savedReportSettings = get_option('hm_psr_report_settings'); if (!isset($savedReportSettings[0])) return false; $prevPost = $_POST; $_POST = $savedReportSettings[0]; $_POST['report_time'] = 'custom'; $_POST['report_start'] = date('Y-m-d', $start); $_POST['report_end'] = date('Y-m-d', $end); $_POST = array_merge($_POST, array_intersect_key($args, $_POST)); if ($output) { echo('<table><thead><tr>'); foreach (hm_sbpf_export_header(null, true) as $heading) { echo("<th>$heading</th>"); } echo('</tr></thead><tbody>'); foreach (hm_sbpf_export_body(null, true) as $row) { echo('<tr>'); foreach ($row as $cell) echo('<td>'.htmlspecialchars($cell).'</td>'); echo('</tr>'); } echo('</tbody></table>'); $_POST = $prevPost; return; } $filename = get_temp_dir().'/Product Sales Report.csv'; $out = fopen($filename, 'w'); if (!empty($_POST['include_header'])) hm_sbpf_export_header($out); hm_sbpf_export_body($out); fclose($out); $_POST = $prevPost; return $filename; } function hm_psrf_report_order_statuses() { $wcOrderStatuses = wc_get_order_statuses(); $orderStatuses = array(); if (!empty($_POST['order_statuses'])) { foreach ($_POST['order_statuses'] as $orderStatus) { if (isset($wcOrderStatuses[$orderStatus])) $orderStatuses[] = substr($orderStatus, 3); } } return $orderStatuses; } /* Review/donate notice */ register_activation_hook(__FILE__, 'hm_psrf_first_activate'); function hm_psrf_first_activate() { $pre = 'hm_psr'; $firstActivate = get_option($pre.'_first_activate'); if (empty($firstActivate)) { update_option($pre.'_first_activate', time()); } } if (is_admin() && get_option('hm_psr_rd_notice_hidden') != 1 && time() - get_option('hm_psr_first_activate') >= (14*86400)) { add_action('admin_notices', 'hm_psrf_rd_notice'); add_action('wp_ajax_hm_psrf_rd_notice_hide', 'hm_psrf_rd_notice_hide'); } function hm_psrf_rd_notice() { $pre = 'hm_psr'; $slug = 'product-sales-report-for-woocommerce'; echo(' <div id="'.$pre.'_rd_notice" class="updated notice is-dismissible"><p>Do you use the <strong>Product Sales Report</strong> plugin? Please support our free plugin by <a href="" target="_blank">making a donation</a>!product-sales-report-for-woocommerce Thanks!</p></div> <script>jQuery(document).ready(function($){$(\'#'.$pre.'_rd_notice\').on(\'click\', \'.notice-dismiss\', function(){jQuery.post(ajaxurl, {action:\'hm_psrf_rd_notice_hide\'})});});</script> '); } function hm_psrf_rd_notice_hide() { $pre = 'hm_psr'; update_option($pre.'_rd_notice_hidden', 1); } ?>
Hi guys, I'm trying to sort an array. The array has information about listings. ID, name, info etc. An unrelated set of data also contains the listing ID's and I have made a function to sort this array and show an new order for the ID's. I now need to sort the original array by this new ID order... This snippet shows that the original listings array can be sorted by link_id: sort($this->links, $this->link->link_id); //This works. It sorts links by link ID! In a foeach loop I have created this: $sleeps_array[] = array("ID" => $link->link_id, "Sleeps" => $sleeps); // Makes an array of arrays of a custom field with listing ID. It makes this: array ( 0 => array ( 'ID' => '9', 'Sleeps' => '2', ), 1 => array ( 'ID' => '3', 'Sleeps' => '4', ), 2 => array ( 'ID' => '6', 'Sleeps' => '6', ), ) I can then sort this array of arrays with this function: function compare_sleeps($a, $b){ return strnatcmp($a['Sleeps'], $b['Sleeps']); } # sort alphabetically by name usort($sleeps_array, 'compare_sleeps'); It then gives me a sorted array according to "Sleeps" (as in, the number of people a property can cater for). It has the correct order of ID to then output but how do I organise the original array by ID with this new array? Sounds complicated, I hope you got that! Cheers, RJP1 Hello, I have several job categories on a recruitment website: $job_category[0]="accountant"; $job_category[1]="php programming"; $job_category[2]="baseball"; these job categories are contained within the urls imediately after the recruiting company's name and before the word "jobs", so we could have the following urls: www.url.com/company_name_accountant_jobs www.url.com/another_company_name_baseball_jobs www.url.com/yet_another_company_name_php programming_jobs Using the array $job_categories and the page path after the foward slash (e.g. yet_another_company_name_php programming_jobs) please could you tell me how to strip out the job category and the company name? (I'll extract the page path using a mod_rewrite) Thanks Stu |