counting occurrences in an array - arrays

I am trying to count the number of occurrences in an array of cart items in Magento.
There are several items in the array, all with a price field (either $0 and $10)
What I'm looking to do, is to display the count of those items that have a price of 0
I currently have:
$session = Mage::getSingleton('checkout/session');
$items_array = $session->getQuote()->getAllItems();
foreach($items_array as $item) {
if ($item->getPrice() == 0) {
echo 'Item is free';
}
else {
}
}
This simply outputs all the free items. Ideally, I'd like to display just the count of such items.
Could I use something like array_count_values, but limit it to only count those values that are 0?

You can do that with several ways, but having that code the most easy one will be:
$session = Mage::getSingleton('checkout/session');
$items_array = $session->getQuote()->getAllItems();
$freeItems = 0;
foreach($items_array as $item) {
if ($item->getPrice() == 0) {
$freeItems++;
}
}
echo "There are $freeItems free items";

$session = Mage::getSingleton('checkout/session');
$items_array = $session->getQuote()->getAllItems();
$free = 0;
$notfree = 0;
foreach($items_array as $item) {
if ($item->getPrice() == 0) {
echo 'Item is free';
$free++;
}
else {
$notfree++;
}
}
echo 'total free items = ' . $free;
echo 'total nonfree items = ' . $notfree;

Related

foreach by quantity in laravel

I develop a ticketing system which user have to choose the quantity of ticket category. I want to save the record to database by the total of quantity. But it seems to be failed. I end up only save the record by category id. Here is the result when I try to return it.
and this is my code in controller.
public function ticket_checkout(Request $request)
{
$ctg_id = $request->cat_id;
$price = $request->price;
$name = $request->name;
$qty = $request->qty;
// return count($qty);
$data = [];
$i = 0;
foreach($qty as $item){
if($qty[$i] != 0){
$data[] = [
"ctg_id" => $ctg_id[$i],
"price" => $price[$i],
"qty" => $item,
];
}
$i++;
}
return $data;
Ticket_checkout::insert($data);
// return $qty;
return view('ticket.index', compact('data','qty'));
}
I wonder if I missing something here? I tried to do looping 'for' by quantity inside the 'foreach' but it seems not working too.

Unable to find if one item exists in array of items and return the necessary message in Perl

I have array of IDs. I have one ID which I want to find if that ID exists in the array of IDs in Perl
I tried the following code:
my $ids = [7,8,9];
my $id = 9;
foreach my $new_id (#$ids) {
if ($new_id == $id) {
print 'yes';
} else {
print 'no';
}
}
I get the output as:
nonoyes
Instead I want to get the output as only:
yes
Since ID exists in array of IDs
Can anyone please help ?
Thanks in advance
my $ids = [7,8,9];
my $id = 9;
if (grep $_ == $id, #ids) {
print $id. " is in the array of ids";
} else {
print $id. " is NOT in the array";
}
You just need to remove the else part and break the loop on finding the match:
my $flag = 0;
foreach my $new_id (#$ids) {
if ($new_id == $id) {
print 'yes';
$flag = 1;
last;
}
}
if ($flag == 0){
print "no";
}
Another option using hash:
my %hash = map { $_ => 1 } #$ids;
if (exists($hash{$id})){
print "yes";
}else{
print "no";
}
use List::Util qw(any); # core module
my $id = 9;
my $ids = [7,8,9];
my $found_it = any { $_ == $id } #$ids;
print "yes" if $found_it;
The following piece of code should cover your requirements
use strict;
use warnings;
my $ids = [7,8,9];
my $id = 9;
my $flag = 0;
map{ $flag = 1 if $_ == $id } #$ids;
print $flag ? 'yes' : 'no';
NOTE: perhaps my #ids = [7,8,9]; is better way to assign an array to variable

How can i get top 15 occurrences in an array and use each value to fetch data from mysql database?

I am currently working on a project (A music website) with PHP Codeigniter. I want to fetch top 15 songs by number of downloads. To my knowledge, I got all unique ID's out ranging from highest to least. But now, I want to use each of these unique ID's to fetch data from another table in the database.
I have tried using for loop; but it seems to only return one of the rows which happens to be the first and highest number of occurrence in the array. The code below echo's the ID's but how can I use each of those ID's to fetch data.
function top15(){
$this->db->select('musiccode');
$result=$this->db->get('downloads');
$query = $result->result_array();
$downloads = array();
if(!empty($query)) {
foreach($query as $row)
{
$musiccode[] = $row['musiccode'];
}
$mode = array_count_values($musiccode);
arsort($mode);
$i = 0;
foreach ($mode as $field => $number) {
$i++;
echo $field." occured ". $number." times <br>";
if ($i == 15) {
break;
}
}
}
}
for ($b=0; $b < count($field); $b++) {
$this->db->where(array('track_musiccode'=> $field));
$field = $this->db->get('tracks');
return $field->result_array();
}
The code above only produce one row for me. I expect to have more than one and according to the number of ID's in the array. Thanks in advance.
For a single column condition, you could use where_in() instead and drop the for loop :
$this->db->where_in('track_musiccode', $field);
$field = $this->db->get('tracks');
return $field->result_array();
Yes Finally i did it. Incase if anyone needs it. this works just fine
function top15(){
$this->db->where('d_month', date('m'));
$this->db->select('musiccode');
$result=$this->db->get('downloads');
$query = $result->result_array();
$downloads = array();
if(!empty($query)) {
foreach($query as $row){
$musiccode[] = $row['musiccode'];
}
$res='';
$count=array_count_values($musiccode);
arsort($count);
$keys=array_keys($count);
for ($i=0; $i < count($keys); $i++) {
$res[] .= "$keys[$i]";
}
$this->db->where_in('track_musiccode', $res);
return $this->db->get('tracks')->result_array();
}
}
And I got this too. If I wasn't going to count occurrences but just iterate the number of downloads which is far more better than counting in other not to over populate the database and make your website work slowly.
function top15(){
$tracks = '';
$this->db->group_by('counter');
$result=$this->db->get('downloads');
$query = $result->result_array();
$counter = '';
$fields = '';
if(!empty($query)) {
foreach($query as $row) {
$counter[] = $row['counter'];
}
rsort($counter);
for ($i=0; $i<=15; $i++) {
$this->db->where('downloads.counter', $counter[$i]);
$this->db->join('tracks', 'tracks.musicid = downloads.musicid');
$fields[] = $this->db->get('downloads')->row_array();
}
return $fields;
}
}
Enjoy...

Get array data and insert into database

I'm trying to get the data in the array that came from another function(that function is extracting the data in the csv file) and when i tried calling the two fields from that array it shows an error that it is unidentified variables.
The $this->csv_process(); as shown on the function action() is the function that extracts the data from the csv file and stores it in an array which is successful since I tried checking it on var_dump();
I also named the two fields as $name and $email as shown below:
Function CSV_process()
public function csv_process()
{
/* variables for openning the csv file */
if (!in_array($extension, $allowed_ext)) {
$this->session->set_flashdata("message", "Sorry, CSV file only.");
} else {
if ($filesize > 0) {
$file = fopen($filename, "r");
$toWrite = array();
$error = false;
$col_size = 2;
$skip = 0;
while ($data = fgetcsv($file, 10000, ","))
{
$skip++;
if ($skip == 1) {
continue;
}
$numofcol = count($data);
if ($numofcol != $col_size ) {
$this->session->set_flashdata("message", "Column count exceeded or missing.");
} else {
$name1 = $data[0];
$name = str_replace("'", "''", $name1);
$email1 = $data[1];
$email = str_replace("'", "''", $email1);
$toWrite[] = [
'name' => $name,
'email' => $email
];
}
}
}
}
return $toWrite;
}
Function Action()
function action(){
$toWrite[] = $this->csv_process();
foreach ($toWrite as $arr) {
list($name, $email) = $arr;
//die(var_dump($arr));
$query = $this->db->query("SELECT * FROM import WHERE name ='$name' AND email = '$email'");
if ($query->num_rows() >= 1) {
} else {
if ($name == "" OR $email == "") {
} else {
if ((filter_var($email, FILTER_VALIDATE_EMAIL)) == FALSE ) {
} else {
$this->db->query("INSERT INTO import(name, email, created_date) VALUES('".$name."', '".$email."', '".date("Y-m-d h-i-s")."')");
$this->session->set_flashdata('message', 'SUCCESS YEAY');
redirect('Clean_csv/index');
}
}
}
$query->free_result();
}
}
Listing arrays doesn't seem to work for here, anyone knows how to extract the data array from $arr?
You don't need to extract the values. You can use each $arr in a bound query. It simplifies the syntax for the select query.
For inserting use CodeIgniter's insert() method. Again, the $arr can be used directly by adding the date to it before the insert is attempted.
I think this will work.
function action()
{
$toWrite[] = $this->csv_process();
foreach($toWrite as $arr)
{
$query = $this->db->query("SELECT * FROM import WHERE name=? AND email=?", $arr);
if($query->num_rows() >= 1)
{}
else
{
if($arr['name'] == "" OR $arr['email'] == "")
{}
else
{
if((filter_var($email, FILTER_VALIDATE_EMAIL)) == FALSE)
{}
else
{
$arr['created_date'] = date("Y-m-d h-i-s");
$this->db->insert("import", $arr);
$this->session->set_flashdata('message', 'SUCCESS YEAY');
//??? redirect('Clean_csv/index');
//Are you sure, you may still have more $arr in $toWrite to process - right?
}
}
}
$query->free_result();
}
}
You need to know what a terrible idea it is to repeatedly run database queries inside a loop. Even though you use free_result() it could be a massive drain on server resources. If your csv file has several thousand items you are severely stressing the database and the server.

How to replace all instances of a word/string in an array with another word/string

I have an array that contains some formatted price totals and is being printed, it is basically keys and values.
The array is called $info['order_total']
How can I loop through all the values and replace all instances of the words 'Collection' & 'Delivery' with 'card charge'
Assuming php:
for ($info['order_total'] as $key=>$value){
if ($value == 'Collection' || $value == 'Delivery'){
$info[$key] = 'card charge';
}
}
or similarly:
for($i = 0; $i<count($info['order_total'];$i++)){
if ($info['order_total'][$i] == 'Collection' ||
$info['order_total'][$i] == 'Delivery'){
$info['order_total'][$i] = 'card charge';
}
}

Resources