Fill Values in multidimensional Array (PHP) - php

I've got a small problem. I'm working on a little package/product-list.
If you're watching a Package, my website should show you which products are in there.
If a product is more than one time in it, the array should be deleted and the value of the leftover array should be + 1 (each deleted array).
So here's my code:
// $products_in_package has all products in it
// First of all, the products come from a db and don't have a count
// So i first give them a count of 1
foreach ($products_in_package as $product => $value) {
$products_in_package[$product]['count'] = intval(1);
}
foreach ($products_in_package as $product) {
$id_to_find = intval($product['ID']);
$product_count = intval($product['count']);
$found_id = 0;
// Now I try to find any ident products
// If found and over 1 time (beacouse he finds the first too of course)
// Then delete this array and count up the products count
for ($i=0; $i <= count($products_in_package); $i++) {
if(intval($products_in_package[$i]['ID']) === $id_to_find){
$found_id++;
if($found_id > 1){
$product_count = $product_count + 1;
$product['count'] = $product_count;
unset($products_in_package[$i]);
array_merge($products_in_package);
while($i > $products_in_package){
$i = 0;
}
}
}
}
}
What I'm getting is the correct multidimensional array but the count is still 1.
What's wrong with the code?
Everytime I try to log the code i'm getting the right integer. (No, I already tried to delete the chache)
But if I log the array out of the loops, I get always the count of 1.

$product is a copy of the array element, so when you do $product['count'] = $product_count you're assigning to a copy, not the original array.
You can fix this by using a reference in the foreach:
foreach ($products_in_package as &$product) {

Related

Create a temporary array in PHP to add to a larger array

I am trying to create a number of arrays to add to a larger array which I will then index two dimensionally (for example my_array[i][j]).
I believe I am having some type of pointing issue... I am iterating through a loop.... at the top of each iteration I instantiate a new array with the same name. When I try and view the output each item in the array appears blank.
Is there a better way for me to instantiate the "temp" arrays to fill the larger (outer) array? Really appreciate any and all help, this community has helped me through so many questions :D
$main_array = array();
for($i = 0; $i < $member_count; $i++)
{
$temp_array = array();
//preform SQL query here
$sql_get_member_transactions = 'some SQL query to go to my DB';
foreach($sql_get_member_transactions as $row)
{
//cannot get array to update here
array_push($temp_array, $row['amount']);
}
array_push($main_array, $temp_array);
}
#***FULL CODE BELOW***
$club_transactions = array();
for($i = 0; $i < $member_count; $i++)
{
#create an array for each member in the club,
#add each memeber's array to a larger array once filled with deposit amounts
#here check if member had a deposit (later we will check ALL transaction types...)
#if no deposit on that date add a zero to their array
$temp_member_transactions = array();
$temp_member = my_members[$i];
$sql_member_transactions = "SELECT * FROM Transactions WHERE Date >= '$first_t_date' AND Date <= '$last_t_date' AND RelatedClubID = 'THH'";
$sql_get_member_transactions = mysqli_query($conn, $sql_member_transactions);
//here we will get all transactions that lie within the
//event-transaction-date-window... in otherwords, the date window
//in the year where members transactions occured
foreach($sql_get_member_transactions as $row)
{
//we only want to include the transaction amount
//in the member-specific array if it belongs to that member
//otherwise see "else"
if($row['T_Owner'] == $temp_member)
{
$z = $row['T_Amount'];
}
else
{
//set to 0 so that we still account for the transaction date
$z = 0;
}
array_push($temp_member_transactions, $z);
}
array_push($club_transactions, $temp_member_transactions );

Sum up all "amount" fields in a Laravel collection

I am trying to get the total amount collected in a month, let's say January.
I am able to retrieve all the created_at fields which were created in the month of January in the $main_data_January variable. The $main_data_January variable contains this type of results.
As you can see, each item has a field called amount.
Problem
I want to retrieve the value of amount field from each item and sum them up. As I'm doing it in the total_earnings_janunary, but this is where I am facing the problem.
By adding both the amounts, the expected result should be 13000, but
the result is 8000. It is only getting only the first value of amount after being in a loop.
$customers = Tag::all();
$total_earnings_janunary = 0;
$query_date = '2017-01-04';
$start_date_janunary = date('Y-01-01', strtotime($query_date));
$end_date_janunary = date('Y-m-t', strtotime($query_date));
foreach ($customers as $customer) {
if (Auth::User()->gym_code == $customer->gym_code ) {
$main_data_janunarys = DB::table('tags')->whereBetween('created_at', [$start_date_janunary,$end_date_janunary])->get();
}
}
for ($i=0; $i <= count($main_data_janunarys); $i++) {
$total_earnings_janunary = $total_earnings_janunary + $main_data_janunarys[$i]->amount;
dd($total_earnings_janunary);
}
Few things to note:
You're querying the Tag model and storing it in $customers. Resulting entities are not customers. Make sure that's intended.
In the first foreach loop, you are overwriting previous value of the $main_data_janunarys over and over. Use break if that's intended.
In the for loop, you are dding early. Move it outside the loop and you'll see your intended results. In the loop exit condition you should be using < instead of <= as you're starting from zero.
To sum up the collection you could just use Collection::sum() method, like: $main_data_janunarys->sum('amount');.
Try this:
$customers = Tag::all();
$total_earnings_janunary = 0;
$query_date = '2017-01-04';
$start_date_janunary = date('Y-01-01', strtotime($query_date));
$end_date_janunary = date('Y-m-t', strtotime($query_date));
foreach ($customers as $customer)
{
if( Auth::User()->gym_code == $customer->gym_code ) {
$main_data_janunarys = DB::table('tags')->whereBetween('created_at', [$start_date_janunary,$end_date_janunary])->get();
}
}
$total_earnings_january = $main_data_januarys->sum('amount');
You can read further about Laravel's Collection here

Recursive Array Cleanup

I have a function called combined which is going to loop through an array of orders. It is specifically searching for someone who placed more than 1 order and matches based on the customer's name and address line 1. If the customer places 2 orders this will catch them and combine them however if they have 3 or more if only catches 2. When I recursively call the function I get an invalid offset error which I do not understand as I thought the array index would refresh on every function call?
function combined(Array $all) {
//find any matching single orders and combine
$count = count($all);
$combinedorder = array();
for($i=1; $i < $count; $i++) {
for($j=1; $j < $count; $j++) {
//if order # is not the same
if(strcasecmp($all[$i][0], $all[$j][0]) !== 0){
//if name matches
if(strcasecmp($all[$i][2], $all[$j][2]) == 0) {
//if address line 1 matches
if(strcasecmp($all[$i][3], $all[$j][3]) == 0) {
$combinedorder[] = array('ordernos' => array($all[$i][0], $all[$j][0]), $all[$i][1], $all[$i][2], $all[$i][3], $all[$i][4], $all[$i][5], $all[$i][6], $all[$i][7], $all[$i][8], $all[$i][9], $all[$i][10], 'orders' => array($all[$i][11], $all[$j][11]));
unset($all[$i]);
unset($all[$j]);
$all = array_merge($all, $combinedorder);
$all = array_values($all);
reset($all);
//this recursive call does not work. undefined offset error
combined($all);
}
}
}
}
}
return $all;
}
You need to re-index the array. You are deleting some of the indexes with unset($all[$i]) and unset($all[$j]). So when the function calls itself and your loop hits the index that you deleted you get the invalid offset error.
To fix it just add this code after you unset some of the indexes to reset the keys of the array.
$all = array_values($all);

Removing an item from an array during a foreach loop

I have the following foreach being performed in PHP.
What I would like to do is instead of the $invalid_ids[] = $product_id; building and then looping around that, I would instead like to remove the entry from array that is being looped around as I'm looping around it..
For example:
If the current $product_id fails any of the test, delete the item from the $current_list array and proceed to the next iteration of the foreach loop.
I tried to do an unset($product_id) while the foreach loop header looked like this: foreach ($current_list as &$product_id) {, but the item item is still in the array.
Does anyone have any ideas on how I can go about doing this?
foreach ($current_list as $product_id) {
// Test 1 - Is the product still active?
// How to test? - Search for a product in the (only active) products table
$valid = $db->Execute("SELECT * FROM " . TABLE_PRODUCTS . " WHERE products_id = " . $product_id . " AND products_status = 1");
// Our line to check if this is okay.
if ($valid->RecordCount <= 0) { // We didn't find an active item.
$invalid_ids[] = $product_id;
}
// Test 2 - Is the product sold out?
if ($valid->fields['products_quantity'] <= 0 and STOCK_ALLOW_CHECKOUT == "false") { // We found a sold out item and it is not okay to checkout.
$invalid_ids[] = $product_id;
}
// Test 3 - Does the product have an image?
if (empty($valid->fields['products_image'])) { // Self explanatory.
$invalid_ids[] = $product_id;
}
}
$product_id isn't the actual data in the array, it's a copy of it. You would need to unset the item from $current_list.
I'm don't know how $current_list is stored, but something like unset($current_list['current_item'] would do the trick. You can use key to select the current_item key in the array.
A similar way of iterating the Array, where you can get the array key, from the PHP key docs...
while ($fruit_name = current($array)) {
if ($fruit_name == 'apple') {
echo key($array).'<br />';
}
next($array);
}
Untested, but something like this...
while ($product_id = current($current_list)) {
// Do your checks on $product_id, and if it needs deleting...
$keyToDelete = key($array);
unset($current_list[$keyToDelete]);
next($current_list);
}
I think this simple code may help you
let's say we have an array of integers and we want to remove all the items that are equal to "2" inside of the foreach loop
$array = [1,2,1,2,1,2,1];
foreach ($array as $key => $value)
{
if($value==2)
unset($array[$key]);
}
var_dump($array);
this shows the following result
array (size=4)
0 => int 1
2 => int 1
4 => int 1
6 => int 1

Get all possible combinations of a PHP Array split in two

Im working on a code for generating a sports teams. I have an array with a list of players and want to store on another array all the possible team cobinations.
To make it simple, lets imagine a tennis match, where you have 4 players that will be split into two teams.
$players = array("Federer","Del Potro","Nadal","Murray");
The output array should look something like this:
$combinations[0][0] = "Federer","Del Potro";
$combinations[0][1] = "Nadal","Murray";
$combinations[1][0] = "Federer","Nadal";
$combinations[1][1] = "Del Potro","Murray";
$combinations[2][0] = "Del Potro","Nadal";
$combinations[2][1] = "Federer","Murray"; .. and so forth..
Any help?
Thanks in advance!
/// -- Edit
This is the code I have so far. All players also have a score and I store this score for later usage. Its not really important. I think I've got it working but im not sure this code gets ALL the possible combinations. What I do is I loop "player count" times and start building teams, after a team is built , I move the second player of the list to the bottom of the array and loop again.
//-- Get the Max Players and the Array of Player Names
$max_players = count($players)/2;
$p = array_keys($players);
for($i=0;$i<=(count($p));$i++){
$tmp = array();
$t=0;
//-- Loop and start placing players into a team. When the max is reached, start placing on the other team.
foreach($p as $player) {
//-- Store player on Team
$tmp[$t][] = $player;
if(count($tmp[$t])==$max_players) {
$t++;
}
}
//-- Get the second player and move it to the bottom of the list.
$second = $p[1];
unset($p[1]);
$p[] = $second;
$p = array_values($p);
//-- Loop thru teams and add the score of each player
foreach($tmp as $key=>$eq) {
$score = 0 ;
foreach($eq as $jug) {
//-- Add Score for each player
$score += floatval($players[$jug]["score"]);
}
//-- Store the sum of scores of all players in team
$tmp[$key]["score"] = $score;
}
//-- Store the Difference between team scores in this "team set"
$tmp["diff"] = abs(round($tmp[0]["score"]-$tmp[1]["score"],2));
$teams[] = $tmp;
}
Just googled and found these results from stackoverflow.com
Get all combinations of a PHP array
algorithm that will take numbers or words and find all possible combinations
PHP: How to get all possible combinations of 1D array?
$player_combination = [];
$match_combination = [];
$players = array("Federer","Del Potro","Nadal","Murray");
for($i = 0; $i< count($players);$i++){
for($j=$i+1;$j<count($players);$j++){
$player_combination[] = [$players[$i],$players[$j]];
}
}
for($i = 0; $i< count($player_combination);$i++){
for($j=$i+1;$j<count($player_combination);$j++){
if(($player_combination[$i][0] !== $player_combination[$j][0]) && ($player_combination[$i][0] !== $player_combination[$j][1])&& ($player_combination[$i][1] !== $player_combination[$j][0]) && ($player_combination[$i][1] !== $player_combination[$j][1]))
$match_combination[] = [$player_combination[$i],$player_combination[$j]];
}
}
my webiste is 9amobile.com

Categories