I have a code that takes posted data from form A and then find the prices of goods and display them. Now i need to do more with the following data in the body of the 2nd form:
Item name
Item Qty
Item Price
The code is here:
<?php
echo "<div style='width:30%; height:auto; border: 2px solid;'>";
echo "<h1>The Items Are...</h1><br>";
//array that will hold the sum of each item cost
$totalAmountArray = array();
foreach ($_POST['basket'] as $name => $value)
{
//indexer for totalAmountArray
$i=0;
if($value > 0){
//echo $name . ": " . $value . "<br>";
$itemPrice;
//reassign
$itemName = $name;
$itemQty = $value;
//sql connection..
mysql_connect();
mysql_select_db("xxxxxx");
$result = mysql_query("SELECT * FROM pricing WHERE item = '".$name."'");
while($row = mysql_fetch_array($result)){
$itemPrice = $row['price'];
/*DEBUGGING*/
echo "Item Name: <b>".$itemName . " </b># ";
echo "<b>".$itemPrice ." </b>X ".$itemQty."<br>";
}//end of while loop
//multiply to get total for this item - store in temp
$temp = $itemQty * $itemPrice;
//store temp at index i in totalAmountArray
array_push($totalAmountArray, $temp);
unset($result);
unset($itemPrice);
unset($itemQty);
unset($temp);
}//end of if-statement
}//end of foreach
echo "<h1>Total Amount:<br></h1> ";
//print_r($totalAmountArray);
$sum;
foreach($totalAmountArray as $perItemPrice){
$sum += $perItemPrice;
}
echo "<b>SR. ".$sum."</b>";
echo "</div>";
?>
I am thinking of storing all the details returned from above foreach's into multidimensional array to have something like this:
[0] => itemName => itemQty => itemPrice <br>
[1] => itemName => itemQty => itemPrice <br>
[2] => itemName => itemQty => itemPrice <br>
[3] => itemName => itemQty => itemPrice <br>
.....
would this be the best way? and how can it be done? I am really unfamiliar with multidimensional arrays in practice (only in theory).
Thanks a lot for the help and advice,
I may be wrong but since you want an advise I just do not see the point on why would you use a two dimensional array in this situation (although I may misunderstood your question and may wrong but I think the best way to solve your problem is to create a class Item in that class has a variables itemName itemQty itemPrice and then store information about every object item in to an array
Hold an array of an array. Making multi dimensional arrays can get a little confusing. For each item, it holds an array of all its data. Another way is to make an object (class), say "items" which holds each piece of data from the form. Each form submission object is then put into an array for sorting and retrieval.
So it would be
[sudo PHP]
class foo
{
int formID
string submitterName
string bar
}
foo->formID = $row['id']
myArray[lastPosition + 1] = foo
for (int i = 0; i < foo.length; i++)
{
echo foo[i]->formID
}
I haven't touched PHP in years, sorry about the wierd half-PHP looking code, just thought I might deliver an answer quickly!
Related
From the following php script:
while($row = mysqli_fetch_array($res, MYSQLI_ASSOC))
{
$category = $row["category"];
$thing = $row["thing"];
echo $category." ".$thing;
echo "<br>";
}
I echo the following lines:
Book book1
Book book2
Chair chair1
Chair chair2
Table table1
but I would like to display as the following result :
Book
book1
book2
Chair
chair1
chair2
Table
table1
I know I have to make a simple loop somewhere here but I don't get the result I want.
Any help would be appreciated. Thanks.
Bonus : I am planning on make all these words clickable to get the them in a variable. If you could insert this tip into your answer it would be nice.
EDIT :
Here is what I tried so far (trying to add also an icon):
while($row = mysqli_fetch_array($res, MYSQLI_ASSOC))
{
foreach($row as $item)
{
echo "<div style='padding-right: 5px' class='glyphicon glyphicon-book'></div>";
echo $item;
echo "<div style='padding-left: 20px'>";
echo "</div>";
echo "<br>";
}
}
$table = array();
while($row = mysqli_fetch_array($res, MYSQLI_ASSOC))
{
if ( !isset( $table[ $row["category"] ] ) ) {
// No category exists, create now
$table[ $row["category"] ] = array();
}
// append to category
$table[ $row["category"] ][] = $row["thing"];
}
// some additional sorting here
/* todo */
print_r($table);
This solution piggybacks off of PHP inherent named keys by "strings" (which behind the scenes are hashed into "buckets". Since your data only shows a data structure that nests one level deep, it is not a recursive solution. But even still, your basic requirement is on category, so will work even if you have a nested data structure.
isset will check if the category exists. If not a new sub array is created which will hold those values.
[] syntax is PHP style to append to an array.
Thanks to #GetSet answer, I could create the right multidimensional array I needed to get the foloowing result:
Array ( [Book] => Array ( [0] => book1 [1] => book2 ) [Chair] => Array ( [0] => chair1 [1] => chair2 ) [Table] => Array ( [0] => table1 ) )
I wanted then to display on a html page like that:
Book
book1
book2
Chair
chair1
chair2
Table
table1
After reading more about PHP arrays, I made out this solution which seem working for me (with the icones):
foreach ($table as $key => $value)
{
echo "<div style='padding-right: 5px; font-size:13px;' class='glyphicon glyphicon-book'></div>";
echo $key;
echo "<div style='height: 2px'></div>";
foreach ($value as $v2)
{
echo "<div style='padding-right: 7px;padding-left: 15px; font-size:11px;' class='fa fa-file-text-o'></div>";
echo $v2;
echo "<div style='height: 5px'></div>";
}
echo "<div style='height: 10px'></div>";
}
Here is the result:
I know have to work on making clickable these words.
Also, I would love to be able to reduce one category by clicking on the book icon but I imagine I have to use JavaScript for that and I don't really know this language.
I have a fuction that returns a row of values as below
fldClientID fldPetID fldName fldBreed fldType fldInactive
> 1406 114 Lola Poodle - Toy Dog 0
1406 5786 Izadora Chihuahua long hair Dog 0
1406 8728 Kurmo Maltese Mix Dog 0
The pet id is different on each pet but same client id I need a method to iterate through the return resurtset and store each pet in a variable like
PETNAME1= lola PETBREED1= Poodle-To
PETNAME2= Izadora PETBREED2 =chihuahua long hair
I have tried this code but stores only the first pet all way through
$pets=$this->readPet();
While(next($pets))
{
$petname1=$pets['fldName'];
$petbreed1=$pets['fldBreed'];
$petname2=$pets['fldName'];
$petbreed2=$pets['fldBreed'];
}
You could show what you have tried already. Some code whould be nice.
Anyway, something like:
$pets = [];
foreach ($rows as $row) {
$pets[$row->fldName] = $row->fldBreed;
}
EDIT: if you want an array with keys as pet names and values as breeds.
EDIT #2: With dynamic variable assignment. This is for educational purposes only. This is a very bad way to work with data iterations.
$counter = 0;
while($counter < count($pets)){
${'petname' . ($counter+1)} = $pets[$counter]['fldName'];
${'petbreed' . ($counter+1)} = $pets[$counter]['fldBreed'];
$counter = $counter + 1;
}
echo $petname1;
echo ' - ' . $petbreed1;
echo "<br>";
echo $petname2;
echo ' - ' . $petbreed2;
A better solution would be using something like array_column() to modify your array.
$pets = array_column($arr, 'fldBreed', 'fldName');
var_dump($pets);
I'm trying to get some specific keys and values from the database. My database entries look like so:
id | name | description | value
------------------------------------------
1 | lang | default language | en
2 | date | date format | YYYY-MM-DD
I want to echo only my name and value fields. I've tried using a nested foreach loop, like so:
foreach($details as $key => $value)
{
foreach($value as $index => $row)
{
echo $index . " / " . $row . "<br />";
}
echo "<br />";
}
But that only echos:
id / 1
name / lang
description / default language
value / en
id / 2
name / date
description / date format
value / YYYY-MM-DD
However, when I add an offset, like so: $index[1], I get this like a instead of name, or e instead of description.
I've previously worked from while loops using mysql_fetch_array, but this would give me a repeated element (say a <tr>) whereas I simply need to extract the value of the field because this will be used to build a form for the user to manage.
Would anyone have a suggestion or different approach for me to do something of the sort ?
EDIT
The query comes from a class file:
// extracted from my queries.class.php
public function my_prefs()
{
global $db;
$query = "SELECT * FROM preferences WHERE value!=NULL";
return $db->select($query);
}
// extracted from the source file
$module_details = $query->my_prefs();
EDIT #2
Perhaps this will help you understand my needs:
foreach($module_details as $key => $value)
{
print_r($module_details);
}
returns:
Array
(
[0] => stdClass Object
(
[id] => 1
[name] => lang
[description] => default language
[value] => en
)
[1] => stdClass Object
(
[id] => 1
[name] => date
[description] => date format
[value] => YYYY-MM-DD
)
}
I need to access only lang / en and date / YYYY-MM-DD.
Sounds like you're looking for something like this:
$tmp = array();
foreach($details as $key => $value)
{
// "name" => "value" dictionary later access
$tmp[$value["name"]] = $value["value"];
echo $value["name"] . " = " . $value["name"]; // echos e.q. "date = YYYY-MM-DD"
echo "<br/>";
}
echo $tmp["date"]; // echos e.q. "YYYY-MM-DD"
Perhaps I misunderstood the question..
But I believe you are trying to access the specific column entry from the array. You can do this by using the keys you are outputting instead of using a numeric index.
foreach($details as $key => $value)
{
echo $value['name'];
echo $value['value'];
echo "<br />";
}
EDIT
If you want to limit the results from your query so you only have the fields you requested replace:
$query = "SELECT * FROM preferences WHERE value!=NULL";
with
$query = "SELECT name, value FROM preferences WHERE value!=NULL";
Finally got around to getting something to work. Here's what I did:
foreach($details as $row)
{
$name = $row->name;
$value = $row->value;
// In order to specify for checkboxes, select, radio, etc.
if($name == "lang")
{
// different info depending on the value
}
else
{
// do something generic here
}
}
Might not be an optimal option, but this works like I need it to work.
I want to run a query that gets all the data from a database then have the data split into arrays for each column. With this I intend to dynamically populate html. I am not very experienced with php and could use some assistance with how to put my query into multiple arrays depending on what column it was in.
Example: For the column name I want an array $itemName[] and it will contain every item name in asc order. Then for the image column I want an array $itemImage[] for every image/image url in the same order.
With this I plan to run a for loop where as x increases it will go through each diff array and pull from the specified location. There are no null values in my DB so I don't need to worry about that.
Any help you can give me with the writing the query into multiple arrays based on the column name is appreciated.
$mPos = array(mPos1, mPos2, mPos3, mPos4);
for (x=0; x<4; x++){
echo "<div class="$mPos[x]"> <div class="$mPos[x] . '_1'">"$title[x]"</div><div class="$mPos1 . '_2'">"$image[x]"</div>
Still doesn't make sense for me to separate it that way, but here you go.
Since you didn't provide a database/table structure, I will assume your db table got the following columns:
itemId | itemName | itemImage | itemDescription
In PHP you loop through the result row for row and populate your arrays like
foreach ( $result AS $row ) {
$itemNames[$row->itemId] = $row->itemName;
$itemImages[$row->itemId] = $row->itemImage;
$itemDescriptions[$row->itemId] = $row->itemDescription;
}
EDIT: After question was updated and now includes the HTML output, I'd suggest something like this.
foreach ( $result AS $row ) {
$items[$row->itemId] = array(
'name' => $row->itemName,
'image' => $row->itemImage,
'description' => $row->itemDescription,
'price' => $row->itemPrice,
'link' => $row->itemLink,
);
}
$x = 0;
while ($x<4) {
$x++;
$item = array_shift($items);
echo '<div class="mPos'.$x.'">
<div class="mPos'.$x.'_1">"'.$item['name'].'"</div>
<div class="mPos'.$x.'_2">"'.$item['price'].'"</div>
<div class="mPos'.$x.'_3"><a href="'.$item['link'].'">
<img src="'.$item['image'].'" /></a>
</div>
</div>';
}
$sth = $dbh->prepare("SELECT itemName, itemImage FROM myTable");
$sth->execute();
$result = $sth->fetchAll();
$myArr = array();
foreach($result as $row){
foreach($row as $colName => $colVal){
$myArr[$colName][] => $colVal;
}
}
echo '<pre>';
print_r($myArr);
echo '</pre>';
Although I do have misgivings about how you're actually approaching this from a design perspective.
I have an array like this:
$tset = "MAIN_TEST_SET";
$gettc = "101";
$getbid = "b12";
$getresultsid = "4587879";
$users["$tset"] = array(
"testcase"=>"$gettc",
"buildid"=>"$getbid",
"resultsid"=>"$getresultsid"
);
Arrays in PHP is confusing me.
I want to display some like this:
MAIN_TEST_SET
101 b12 4587879
102 b13 4546464
103 b14 5545465
MAIN_TEST_SET3
201 n12 45454464
MAIN_TEST_SET4
302 k32 36545445
How to display this?
Thanks.
print_r($users)
That will print your array out recursively in an intuitive way. See the manual: http://us2.php.net/manual/en/function.print-r.php
If you want to print it in the specific way you formatted it above you're going to have to write a custom function that uses foreach looping syntax like this:
<?php
echo "<table>";
foreach($users as $testSetName=>$arrayOfTestCases){
echo "<tr><td>".$testSetName."</td></tr>";
foreach($arrayOfTestCases as $k=>$arrayOfTestCaseFields){
//$arrayOfTestCaseFields should be an array of test case data associated with $testSetName
$i = 0;
foreach($arrayOfTestCaseFields as $fieldName => $fieldValue){
//$fieldValue is a field of a testcase $arrayOfTestCaseFields
if($i == 0){
//inject a blank table cell at the beginning of each test case row.
echo "<tr><td> </td>";
$i++;
}
echo "<td>".$fieldValue."</td>";
}
echo "</tr>";
}
}
echo "</table>";
?>
Your data should be composed as follows:
$tset = "MAIN_TEST_SET";
$gettc = "101";
$getbid = "b12";
$getresultsid = "4587879";
$users[$tset] = array();
$users[$tset][] = array( "testcase"=>"$gettc",
"buildid"=>"$getbid",
"resultsid"=>"$getresultsid"
);
$users[$tset][] = ... and so forth ...
To fix the data structure you present (as Victor Nicollet mentions in his comment) you need something like this:
$users = array(); // Create an empty array for the users? (Maybe testsets is a better name?)
$testset = array(); // Create an empty array for the first testset
// Add the test details to the testset (array_push adds an item (an array containing the results in this case) to the end of the array)
array_push($testset, array("testcase"=>"101", "buildid"=>"b12", "resultsid" => "4587879"));
array_push($testset, array("testcase"=>"102", "buildid"=>"b13", "resultsid" => "4546464"));
// etc
// Add the testset array to the users array with a named key
$users['MAIN_TEST_SET'] = $testset;
// Repeat for the other testsets
$testset = array(); // Create an empty array for the second testset
// etc
Of course there are much more methods of creating your data structure, but this one seems/looks the most clear I can think of.
Use something like this to create a HTML table using the data structure described above.
echo "<table>\n";
foreach($users as $tsetname => $tset)
{
echo '<tr><td colspan="3">'.$tsetname.'</td></tr>\n';
foreach($tset as $test)
echo "<tr><td>".$test['testcase']."</td><td>".$test['buildid']."</td><td>".$test['resultsid']."</td></tr>\n";
}
echo "</table>\n";
The first foreach iterates over your test sets and the second one iterates over the tests in a test set.
For a short uncustomisable output, you can use:
print_r($users)
alternatively, you can use nested loops.
foreach($users as $key => $user) {
echo $key . "<br />"
echo $user["testcase"] . " " . $user["buildid"] . " " . $user["resultsid"];
}
If you are not outputting to html, replace the <br /> with "\n"