Can't Sort PHP Array [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Can anybody tell me why I can't get this to work?
I am simply trying to sort my arrays from highest to lowest.
$stuff[] = "100";
$stuff[] = "104";
$stuff[] = "102";
$stuff[] = "103";
$stuff[] = "101";
$stuff[] = "99";
echo "Largest: " . max($stuff) . " <br> \n";
arsort($stuff);
echo "0 : " . $stuff[0] . " <br> \n";
echo "1 : " . $stuff[1] . " <br> \n";
echo "2 : " . $stuff[2] . " <br> \n";
echo "3 : " . $stuff[3] . " <br> \n";
echo "4 : " . $stuff[4] . " <br> \n";
echo "5 : " . $stuff[5] . " <br> \n";

arsort() is sorting your array, but it also conserve the keys of each value. Witch mean the key 0 will still answer with 100, and not the first element !
With a foreach, you would see them in correct order.
foreach ($stuff as $value) {
echo $value . "<br>\n";
}
OR
You can also use rsort() that will not be associative, which mean the keys won't have the same values after it.

Related

How to echo a letter multiple times, changing more then one variable in it for each new print?

Hello all! This is my first question in stackoverflow so I hope I follow the rules good enough. :)
For my PHP class I have an exercise that makes it difficult for me: Text with about 4 variables in it, all are stored in arrays (one array for each variable, 3 values for each variable).
Position [0] of each array goes in the first echo text, position [1] of each array goes in the second text and so on.
How to echo the text 3 times using all values stored in the array? In the code I must use the main text only 1 time.
$u_name = array('student' => 'Joe','lecturer' => 'Kate', 'assistant' => 'Martin');
$course_name = array('PHP', 'CSS', 'HTML');
$role = array('student', 'lecturer', 'assistant');
echo "Hi," . $u_name['student'] . "! You've been approved to take part in course " . $course_name[0] . " as a " . $role[0] . ". The course " . $course_name[0] . " will last for two days.";
echo "<br>";
echo "Hi," . $u_name['lecturer'] . "! You've been approved to take part in course " . $course_name[1] . " as a " . $role[1] . ". The course " . $course_name[1] . " will last for two days.";
echo "<br>";
echo "Hi," . $u_name['assistant'] . "! You've been approved to take part in course " . $course_name[2] . " as a " . $role[2] . ". The course " . $course_name[2] . " will last for two days.";
This is what I did by myself, but as you see in the code I have 3 times the main text.
Thank you in advance.
Normally you go trough arrays with some type of a loop.
To name a few types of loops:
for
while
foreach
In this case the perfect fit is a foreach loop.
It simply goes through each element of the array, but because you have a associative array and two indexed array you also need a counter.
$counter = 0;
foreach($u_name as $key=>$value){
echo "Hi, " . $value . "! You've been approved to take part in course " . $course_name[$counter] . " as a " . $role[$counter] . ". The course " . $course_name[$counter] . " will last for two days.";
echo "<br>";
$counter++;
}
If still are any questions left, don't mind to ask.

String Length Issue [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I have four string length statements I am trying to validate,but only two are working.
$name = "mike";
$age = "54";
$city = "Chicago";
$building = "Madadnock";
$lengthOfString1 = strlen ( $name );
echo "String length of 'name' " . $lengthOfString1 . "</br>";
$lengthOfString2 = strlen ( $age );
echo "String length of 'age' " . $lengthOfString2 . "</br>";
$lengthOfString3 = strlen ( $city );
echo "String length of 'city' " . $lengthOfstring3 . "</br>";
$lengthOfString4 = strlen ( $building );
echo "String length of 'building' " . $lengthOfstring4 . "</br>";
The top two are the only ones that work. Any help would be great!
variables in PHP are case sensitive
$lengthOfString4 vs $lengthOfstring4
^ ^
The problem lies in variable names. The variable names in PHP are case-sensitive.
$lengthOfString3 = strlen ( $city );
echo "String length of 'city' " . $lengthOfString3 . "</br>";
$lengthOfString4 = strlen ( $building );
echo "String length of 'building' " . $lengthOfString4 . "</br>";
Fixed it.

Showing a limited number of mysqli_fetch_assoc array

I want to create an array with the help of MYSQL and display it the following way:
while ($array = mysqli_fetch_assoc($res))
{
echo $array["first_name"] . ", "
. $array["last_name"] . ", "
. $array["personal_id"] . ", "
. $array["salary"] . ", "
. $array["birthday"] . "<br />";
}
To improve usability, I only want to display 10 results, put a link to the next 10 results at the bottom and display these on another page.
How do I have to change the while-condition in order to only display the first 10 results of my result?
I tried searching for a solution but I couldn't find anything that fits my needs, so any help is appreciated!
Thanks in advance!
Check offset and limit conditions in mysql.
Example: to show 16 - 26 records from result query.
$sql = "SELECT * FROM Table LIMIT 10 OFFSET 15"
If what you want is just a way to break out of the loop after the first 10 results.
$counter = 1;
while (($array = mysqli_fetch_assoc($res)) || ($counter < 10))
{
echo $array["first_name"] . ", "
. $array["last_name"] . ", "
. $array["personal_id"] . ", "
. $array["salary"] . ", "
. $array["birthday"] . "<br />";
$counter++;
}

Resolve PHP post string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have the following post string:
Name=John&Age=33&Question1=What's+your+gender%3F&Answer1=Male&Question2=What's
+your+education%3F&Answer2=Graduate
I'm going to have randomly generated amount of questions each time so I won't be able to know number of passed variables. Thus, I am searching for a solution something like:
foreach($postItem as $varr) {
echo $varr["name"].": ".$varr["value"]."<br />";
}
Post them as answer[1], answer[2] etc instead of answer1, answer2, and PHP will turn them into an array for you.
//parse query string to an array ($output)
parse_str($postString, $output);
echo $output['Name'] . ': ' . $output['Age'] . '<br />';
//process questions
$i = 1;
while (array_key_exists('Question' . $i, $output)) {
echo $output['Question' . $i] . ': ' . $output['Answer' . $i] . '<br />';
$i++;
}
function used http://php.net/parse_str

Get sum of php array

I am adding elements from my SQL query to an associative array and printing them as is shown below;
foreach ($db->query($sql) as $row)
{
?>
<p>
<?php
//Print details of each row
echo "Sale Date: " . $row['saleDate'] . "<br />" .
"Sale Price: " . $row['salePrice'] . "<br />" .
"Buyers Email: " . $row['userEmail'] . "<br />";
?>
</p>
i would like to be able to get the sum of salePrice for elements which match my SQL query.
i know i can use the SQL sum command to get the sum of my whole salePrice column in sql, but i would only like to see the sum of the elements which match my query. Is there a simple way to do this?
Thanks.
$summary = 0;
foreach ($db->query($sql) as $row) {
?>
<p>
<?php
//Print details of each row
echo "Sale Date: " . $row['saleDate'] . "<br />" .
"Sale Price: " . $row['salePrice'] . "<br />" .
"Buyers Email: " . $row['userEmail'] . "<br />";
$summary += $row['salePrice'];
?>
</p>
<?
}
echo 'Summary: '.$summary;
?>
$sum = 0;
foreach ($db->query($sql) as $row)
{
?>
<p>
<?php
$sum += floatval($row['salePrice']);
//Print details of each row
echo "Sale Date: " . $row['saleDate'] . "<br />" .
"Sale Price: " . $row['salePrice'] . "<br />" .
"Buyers Email: " . $row['userEmail'] . "<br />";
?>
</p>
Use this $sum variable for calculation
you can add that codition in sql query only and get sum(yourfield) in query only.
or else if you want to list all $row and sum the price of selected then
$sum = 0;
foreach ($db->query($sql) as $row)
{
?>
<p>
<?php
if()// your condition here
{
$sum += floatval($row['salePrice']);
}
//Print details of each row
echo "Sale Date: " . $row['saleDate'] . "<br />" .
"Sale Price: " . $row['salePrice'] . "<br />" .
"Buyers Email: " . $row['userEmail'] . "<br />";
?>
</p>
You can also do this simply in mysql (it may even be faster).
Assuming a data structure like this:
CREATE TABLE tbl_sales (
buyers_email VARCHAR(50), /* probably should make this foreign key of tbl_buyer */
sale_price DECIMAL(7,2),
sale_date TIMESTAMP
);
An $sql query like this will do:
SELECT SUM(sale_price) AS total_sale FROM tbl_sales;
Then in PHP:
$query = $dbh -> exec ($sql);
$query -> setFetchMode(PDO::FETCH_ASSOC);
$results = $query -> fetchAll();
$total = $results[0]["total_sale"];
I think you should use the right tool for the right Job .. since you are calling MySQL it already has a SUM function
SELECT SUM(salePrice) as total
That would get the Job done much faster
The simplest method by which to do this is to use the sql command.
SELECT SUM(salePrice) as sum
Then calling sum will give you the sum of salePrice for elements which match your associative array

Categories