How do i add items into a multidimensional array? Basically i am making an application which calculates what people are buying in a suppermarket and how much of it.
Sue buys 2 tubs of butter and 1.
toothpaste
John buys 1 peach and 1 banana.
I think the array would look something like this
$sue[butter] = array();
$sue[butter][] = 2;
$sue[toothpaste] = array();
$sue[toothpaste][] = 1;
$john[peach] = array();
$john[peach][] = 1;
$john[banana] = array();
$john[banana][] = 1;
My current code can only record the item and the item quantity.
public $items = array();
public function AddItem($product_id)
{
if (array_key_exists($product_id , $this->items))
{
$this->items[$product_id] = $this ->items[$product_id] + 1;
} else {
$this->items[$product_id] = 1;
}
}
I just dont know how to put this inside an array for each person.
Thanks!
Instead of doing this, you might find it easier to encapsulate into a class. For instance, have each person be a class, and then give them attributes.
Once you get into multidimensional arrays, it becomes more difficult to maintain your code.
For instance (this is pseudocode):
class Customer {
//this is an array of FoodItem objects.
private $foodItems[];
// any other methods needed for access here
}
class FoodItem {
//could be a String, or whatever it needs to be
private $itemType;
//the number of that item purchased
private $numPurchased;
}
Hm, maybe I fail to see the multi-dimensionality here?
$sue = array();
$sue['butter'] = 2;
$sue['toothpaste'] = 1;
$john = array();
$john['peach'] = 1;
$john['banana'] = 1;
I think the function you've shown would work with the above.
You dont need to create another array to hold the number of items like you did here:
$sue[butter] = array();
$sue[butter][] = 2;
I think something like this would work:
$customers[sue][butter] = 2;
$customers[sue][toothpaste] = 1;
$customers[john][peach] = 1;
$customers[john][banana] = 1;
This way you create an array of customer names. Then in each customer array you have an array of their products. Then each product holds the number of that product the customer bought.
$data = array();
$data["persons"] = array("Sue","John");
$data["articles"] = array("butter","toothpaste","peach","banana");
$data["carts"] = array();
$data["carts"][0][0] = 2; // sue's 2 butter packets
$data["carts"][0][1] = 1; // sue's 1 tooth paste
$data["carts"][1][2] = 1; // john's peach
$data["carts"][1][3] = 1; // john's banana
Related
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 );
I want to rearrange order of an array ($activity_names)
$next_ordernr = 1000;
foreach( $activity_names as $term_id=>$activityarea_name) {
$onr = $custom_ordernrs[$term_id];
if ((int)$onr === 0) {$onr = $next_ordernr; $next_ordernr++;}
$activity_names[$term_id]['reorder']= $onr;
}
I understand how I should do it, but I'm kind of stuck when trying to add a key to an existing array (which should be the easy part ;-)).
I get this warning:
Warning: Illegal string offset 'reorder' in ....
The 'reorder' key does not exist before, but I thought I could like above just to add the key reorder into that existing array.
$next_ordernr = 1000;
foreach( $activity_names as $term_id=>$activityarea_name) {
$onr = $custom_ordernrs[$term_id];
if ((int)$onr === 0) {$onr = $next_ordernr; $next_ordernr++;}
$activity_names[$term_id]= $onr;
}
Works as expected.
I just want to add a key to an existing array. What am I overlooking?
UPDATE
$activity_names array could look like this:
$activity_names[24] = 'Activityname1';
$activity_names[36] = 'Activityname2';
$activity_names[14] = 'Activityname3';
$activity_names[54] = 'Activityname4';
$activity_names[104] = 'Activityname5';
UPDATE2
When thinking of it, I am maybe approaching this incorrectly...
I want to rearrange order of $activity_names array based on $custom_ordernrs - array
The $activity_names and $custom_ordernrs - array could look like this:
$activity_names[24] = 'Activityname1';
$activity_names[36] = 'Activityname2';
$activity_names[14] = 'Activityname3';
$activity_names[54] = 'Activityname4';
$activity_names[104] = 'Activityname5';
$custom_ordernrs[24] = 5;
$custom_ordernrs[36] = 4;
$custom_ordernrs[14] = 3;
$custom_ordernrs[54] = 2;
$custom_ordernrs[104] = 1;
should result in this order in array:
$activity_names[104] = 'Activityname5';
$activity_names[54] = 'Activityname4';
$activity_names[14] = 'Activityname3';
$activity_names[36] = 'Activityname2';
$activity_names[24] = 'Activityname1';
$activity_names['your_key']= $value;
If someone stumbles upon the same issue...
Approached the issue in another way. I rearranged the $custom_ordernrs-array instead (instead of trying to add a key to existing array $activity_names) and based on that create a temporary array and then replaced $activity_names with that temporary - array:
asort($custom_ordernrs); //Sort from low to high and maintin indexes(keys)
$temp = array();
foreach($custom_ordernrs as $term_id=>$an) {
$temp[$term_id] = $activity_names[$term_id];
}
$activity_names = $temp;
I am facing problem to retrieve records in descending order with pagination limit from amazon dynamodb as in mysql.
Now I am using the following script, but it gives unordered list of records. I need the last inserted id is on top.
$limit = 10;
$total = 0;
$start_key = null;
$params = array('TableName' => 'event','AttributesToGet' =>array('id','interactiondate','repname','totalamount','fooding','nonfooding','pdfdocument','isMultiple','payment_mode','interaction_type','products','programTitle','venue','workstepId','foodingOther','interaction_type_other'), 'ScanFilter'=> array('manufacturername' => array("ComparisonOperator" => "EQ", "AttributeValueList" => array(array("S" => "$manufacturername")))),'Limit'=>$limit );
$itemsArray = array();
$itemsArray = array();
$finalItemsArray = array();
$finalCRMRecords = array();
do{
if(!empty($start_key)){
$params['ExclusiveStartKey'] = $start_key->getArrayCopy();
}
$response = $this->Amazon->Dynamodb->scan($params);
if ($response->status == 200) {
$counter = (string) $response->body->Count;
$total += $counter;
foreach($response->body->Items as $itemsArray){
$finalItemsArray[] = $itemsArray;
}
if($total>$limit){
$i =1;
foreach($response->body->Items as $items){
$finalItemsArray[] = $items;
if($i == $limit){
$start_key = $items->id->{AmazonDynamoDB::TYPE_NUMBER}->to_array();
$finalCRMRecords['data'] = $finalItemsArray;
$finalCRMRecords['start_key'] = $start_key;
break;
}
$i++;
}
}elseif($total<$limit){
$start_key = $response->body->LastEvaluatedKey->to_array();
}else{
$finalCRMRecords['data'] = $finalItemsArray;
if ($response->body->LastEvaluatedKey) {
$start_key =$response->body->LastEvaluatedKey->to_array();
break;
} else {
$start_key = null;
}
$finalCRMRecords['start_key'] = $start_key;
}
}
}while($start_key);
Regards
Sandeep Kumar Sinha
A Scan operation in DynamoDB can not change the sorting of the returned items. Also is Scan a pretty expensive operation as it always requires to read the whole table.
If you want to take advantage of DynamoDB, here's one advice:
Instead of looking for information, try to just find it.
In the sense of, use lookups instead of scan/query to get the information you need.
As an example, if you have a table that stores Events. Just store all events in that table, with their EventId as HashKey. Then you can have a second table EventLookups to store lookups to EventIds. In the EventLookups table you could put an Item like LookupId: LATEST-EVENT referencing some EventId: .... Every time you insert new events you can update the LATEST-EVENT entry to point to a newer Event. Or use a SET to store the latest 50 EventIds events in one Item.
-mathias
Code is below if I run one value in the array the results are correct if I run more than one value the results are of the price is incorrect its like it has messed around with the values somewhere ?? help appreciated
$dido=array('42204131','22204131');
foreach($dido as $did):
$query = "select * from dispatch,link where lid=dlid and did=$did";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$vanc1=$row['vanc1'];
$vanc2=$row['vanc2'];
$vanc3=$row['vanc3'];
$vanc4=$row['vanc4'];
$vanc5=$row['vanc5'];
$anc1=$row['anc1'];
$anc2=$row['anc2'];
$anc3=$row['anc3'];
$anc4=$row['anc4'];
$anc5=$row['anc5'];
// price anc1
$querypanc1 = "select pprice from products where pid=$anc1";
$resultpanc1 = mysql_query($querypanc1);
while($row = mysql_fetch_array($resultpanc1))
{
$priceanc1=$row[pprice];
$tpriceanc1=$vanc1*$priceanc1;
}
// price anc2
$querypanc2 = "select pprice from products where pid=$anc2";
$resultpanc2 = mysql_query($querypanc2);
while($row = mysql_fetch_array($resultpanc2))
{
$priceanc2=$row[pprice];
$tpriceanc2=$vanc2*$priceanc2;
}
// price anc3
$querypanc3 = "select pprice from products where pid=$anc3";
$resultpanc3 = mysql_query($querypanc3);
while($row = mysql_fetch_array($resultpanc3))
{
$priceanc3=$row[pprice];
$tpriceanc3=$vanc3*$priceanc3;
}
// price anc4
$querypanc4 = "select pprice from products where pid=$anc4";
$resultpanc4 = mysql_query($querypanc4);
while($row = mysql_fetch_array($resultpanc4))
{
$priceanc4=$row[pprice];
$tpriceanc4=$vanc4*$priceanc4;
}
// price anc5
$querypanc5 = "select pprice from products where pid=$anc5";
$resultpanc5 = mysql_query($querypanc5);
while($row = mysql_fetch_array($resultpanc5))
{
$priceanc5=$row[pprice];
$tpriceanc5=$vanc5*$priceanc5;
}
$gtprice=$tpriceanc1+$tpriceanc2+$tpriceanc3+$tpriceanc4+$tpriceanc5;
$qrygt="UPDATE dispatch SET gtprice=$gtprice WHERE did=$did";
$resultgt=#mysql_query($qrygt);
}
endforeach;
1) The only possible issue I could spot in your code, is that when some of your select pprice from products where pid ... queries do not return any data, you retain value of $tpriceancX from previous iteration.
2) Also (out of topic) you can replace your 5 blocks of repeated code with for loop.
$gtprice = 0;
for ($i = 1; $i <= 5; $i++)
{
$querypanc = "select pprice from products where pid=".$row["anc$i"];
$resultpanc = mysql_query($querypanc);
while($pancrow = mysql_fetch_array($resultpanc))
{
$priceanc=$pancrow[pprice];
$tpriceanc=$row["vanc$i"]*$priceanc;
$gtprice += $tpriceanc;
}
}
Your first and biggest problem is the copy-pasta nature of your code. Let's try and break down what you're doing:
Setting up a list of ids
Running a query on those ids
Putting the results into an array
Running a separate query on each of those results
You are also using some very janky syntax. (ie foreach($foo as $bar):).
Break these things down into methods. What is a method? It takes an input and transforms it into an output.
//returns an array of price information
public function getPrices($idArray) { //note the good method and parameter names!
//do stuff
}
Now that we know what we are doing, we can start to fill in the implementation details:
public function getPrices($idArray) {
foreach($idArray as $id) {
//somehow get the gross-scale information
//then put it in a data object
//then call a function to get specific information
}
}
What should that sub-method do? Lets look at your current code snippet:
// price anc1
$querypanc1 = "select pprice from products where pid=$anc1";//sets up sql query
$resultpanc1 = mysql_query($querypanc1); //runs the query
while($row = mysql_fetch_array($resultpanc1)) { //for each result
$priceanc1=$row[pprice]; //gets the price
$tpriceanc1=$vanc1*$priceanc1; //calculates some other price
}
Those last two lines really suggest an object but maybe that's too heavyweight for your purpose. The first two lines are boiler plate you repeat endlessly. Lets write a function!
public function getPrices($name, $pid, $multiplier) {
$sqlQuery = "SELECT pprice FROM products WHERE pid=$pid";
$result = mysql_query($sqlQuery);
$prices = array();
while ($row = mysql_fetch_array($result) {
$key = "price".$name;//$key will be something like 'priceanc1'
$prices[$key] = $row[pprice];
$tkey = "tprice".$name;
$prices[$tkey] = $prices[$key] * $multiplier;
}
}
Now, this function is a bit unclean because it tries to do two things at once (queries the database and then massages the data into a usable array) but I wanted it to resemble what you were doing. With this function written we can go back to our higher level function an call it:
public function getPrices($idArray) {
foreach($idArray as $id) {
$sqlQuery = "SELECT * from dispatch, link WHERE lid=dlid and did=$id";
$prices = array();
while ($row = mysql_fetch_array($result) {
for ($idx = 1; $idx <= 5; $idx++) {
$name = "anc".$idx;
$pid = $row[$name];
$multiplier = $row["vanc".$idx];
$priceArray = getPrices($name, $pid, $multiplier);
$prices = array_merge($prices, $priceArray);
}
}
}
//put a var_dump here to check to see if you're getting good results!
return $prices;//Should be the aggregated prices you've gotten from the db
}
Now, that is what you're attempting to do, but I admit I don't understand how your database is set up or what your variables actually mean. Pressing on! We also note that unnecessary massaging of data falls away.
You can call this like so:
$ids = array();
$ids[] = 42204131;
$ids[] = 22204131;
$prices = getPrices($ids);
var_dump($prices);//shows the result of your work
Now that you have the prices, you can pass them to another function to run the update:
updatePrices($prices);
I'll let you write that part on your own. But remember; break down what you're doing and have repeated elements be handled by the same function. The real lesson to learn here is that programming is really communicating: your code doesn't communicate anything because there is so much repeated noise. Use good variable names. Tighten what you're doing down to functions with single tasks. This way anyone reading your code (including you!) will know what you're trying to do and where you've gone wrong.
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