I have not coded in many years and have decided to make my own golf statistics program.
I have an issue with going through an array and getting the data I want out. I'm guessing it is very simple but I'm very rusty and tried to read myself to this. Thankful for any help.
For the below code I want $dismade to be 8 it now returns 4?
<?php
$score = array(
"4" => "4",
"3" => "4",
"4" => "4"
);
$dismade = 0;
foreach ($score as $stroke => $dis) {
if($stroke == 4) {
$dismade = $dis + $dismade;
}
}
echo $dismade;
?>
UPDATE!!
That worked well. Thanks. Now i have another issue where i would need to do this 18 times. I tried doing like below without luck. What i want to do is to check the foreach array 1-18. They will all be the same with 9 keys inside. Am i thinking correctly on this? The below only gets the first position. $row[fp1] for example will always be key 2 but can have alot of values inside which i want to go through and add to $gir and then move on to fp2 and so on to 18 and add into $gir array. I hope my question makes sense.
$hole1 = array();
$hole2 = array();
$result = mysql_query($sql) or die ("Couldn't select table at!!");
while ($row = mysql_fetch_array($result)) {
$hole1[$row[rid]] = array($row[s1],$row[p1],$row[gir1],$row[ngir1],$row[fp1],$row[fw1],$row[ud1],$row[ss1],$row[pen1]);
$hole2[$row[rid]] = array($row[s2],$row[p2],$row[gir2],$row[ngir2],$row[fp2],$row[fw2],$row[ud2],$row[ss2],$row[pen2]);
}
mysql_free_result($result);
$gir = array();
foreach (array_combine($hole1,$hole2) as $value) {
if($value[2] == 1) {
array_push($gir,$value[4] );
}
}
print_r ($gir);
There is a problem with your $score keys. As you can see you have a duplicate key "4".
Try something like:
$score = array([4,4], [3,4], [4,4]);
$dismade = 0;
foreach ($score as $value) {
if($value[0] == 4) {
$dismade += $value[1];
}
}
echo $dismade;
Have a nice day.
Because you have an duplicate key "4" in your array, since every key is unique in
array so the third line "4" => "4" will overlap the first line within array.
Related
I am using Laravel, however in this case, I think that is irrelevant.
I have 1 array, $materials pulled from a form using $materials = $request->except() which delivers 2 sub arrays, product_code and quantity. So $materials looks like this:
{
"product_code":
[
"123",
"234",
"128"
],
"quantity":
[
"50",
"50",
"50"
]
}
Ok - I need to do an update of the DB table. The table has 2 columns, 'product_code' and 'quantity'
I was thinking I need a foreach loop to update each row:
product_code => Quantity
Problem: How do I update my DB, when the array is not organised in a
$key =>value pair ?
Secondly, is using a foreach() the best way to do it ? I have about 30 products.
Currently I have a foreach loop, which I can not see working for a DB update:
foreach($materials as $key=>$value) {
echo $key."<br>";
foreach ($value as $k=>$v) {
echo($v)."<br>";
}
}
And I get this out of it:
product_code
123
234
128
quantity
50
50
50
Many thanks !
$ids = $request->get('product_code');
$qty = $request->get('quantity');
foreach($ids as $key => $id) {
DB::table('product')->where('product_code', $id)->update(['quantity' => $qty[$key] ]);
}
You could always just do a for loop like the following (if your data is not in json then just ignore the json decode:
<?php
$json = '{"product_code": ["123","234","128"],"quantity": ["50", "50", "50"]}';
$data = json_decode($json, true);
for($i = 0; $i < sizeof($data['product_code']); $i++)
{
echo "UPDATE stuff with the ID " . $data['product_code'][$i] . " and the quantity " . $data['quantity'][$i] . "<br />";
}
?>
This will print
I have a 2 dimensional array. Each subarray consists out of a number of options. I am trying to write a script which picks one of these options for each row. The chosen options have to be unique. An example:
$array = array(
1 => array(3,1),
2 => array(3),
3 => array(1,5,3),
);
With a solution:
$array = array(
1 => 1,
2 => 3,
3 => 5,
);
I have finished the script, but i am not sure if it is correct. This is my script. The description of what i am doing is in the comments.
function pickUnique($array){
//Count how many times each option appears
$counts = array();
foreach($array AS $options){
if(is_array($options)){
foreach($options AS $value){
//Add count
$counts[$value] = (isset($counts[$value]) ? $counts[$value]+1 : 1);
}
}
}
asort($counts);
$didChange = false;
foreach($counts AS $value => $count){
//Check one possible value, starting with the ones that appear the least amount of times
$key = null;
$scoreMin = null;
//Search each row with the value in it. Pick the row which has the lowest amount of other options
foreach($array AS $array_key => $array_options){
if(is_array($array_options)){
if(in_array($value,$array_options)){
//Get score
$score = 0;
$score = count($array_options)-1;
if($scoreMin === null OR ($score < $scoreMin)){
//Store row with lowest amount of other options
$scoreMin = $score;
$key = $array_key;
}
}
}
}
if($key !== null){
//Store that we changed something while running this function
$didChange = true;
//Change to count array. This holds how many times each value appears.
foreach($array[$key] AS $delValue){
$counts[$delValue]--;
}
//Remove chosen value from other arrays
foreach($array AS $rowKey => $options){
if(is_array($options)){
if(in_array($value,$options)){
unset($array[$rowKey][array_search($value,$options)]);
}
}
}
//Set value
$array[$key] = $value;
}
}
//validate, check if every row is an integer
$success = true;
foreach($array AS $row){
if(is_array($row)){
$success = false;
break;
}
}
if(!$success AND $didChange){
//Not done, but we made changes this run so lets try again
$array = pickUnique($array);
}elseif(!$success){
//Not done and nothing happened this function run, give up.
return null;
}else{
//Done
return $array;
}
}
My main problem is is that i have no way to verify if this is correct. Next to that i also am quite sure this problem has been solved a lot of times, but i cannot seem to find it. The only way i can verificate this (as far as i know) is by running the code a lot of times for random arrays and stopping when it encounters an insolvable array. Then i check that manually. So far the results are good, but this way of verication is ofcourse not correct.
I hope somebody can help me, either with the solution, the name of the problem or the verification method.
I'm having trouble trying to remove null values from an array using values from the database. These null values are usually found within the 'answers'.. Code below:
$getQuestions = mysql_logging_query("SELECT fq.`question_id`, fq.`ques_form_id`, fq.`question_body`, fq.`type`, fq.`answer1`, fq.`answer2`, fq.`answer3`, fq.`answer4`, fq.`answer5`, fq.`answer6`, fq.`min_validation`, fq.`max_validation`
FROM QuestionnaireFormQuestions fq
LEFT JOIN QuestionnaireForms f
ON f.`form_id` = fq.`ques_form_id`
WHERE f.`active` = 1
AND f.`form_id` = '".mysql_real_escape_string($form_id,$this->dbcon)."'
",$this->dbcon);
if($getQuestions && mysql_num_rows($getQuestions)>0 && mysql_error($this->dbcon)=="")
{
$get_questions_array = array();
while($getQuestions && $getQuestions_rec=mysql_fetch_assoc($getQuestions))
{
$get_questions_array[] = array('question_id' => $getQuestions_rec['question_id'],
'related_form_id' => $getQuestions_rec['ques_form_id'],
'question_body' => $getQuestions_rec['question_body'],
'question_type' => $getQuestions_rec['type'],
'possible_answer1' => $getQuestions_rec['answer1'],
'possible_answer2' => $getQuestions_rec['answer2'],
'possible_answer3' => $getQuestions_rec['answer3'],
'possible_answer4' => $getQuestions_rec['answer4'],
'possible_answer5' => $getQuestions_rec['answer5'],
'possible_answer6' => $getQuestions_rec['answer6'],
'min_validation' => $getQuestions_rec['min_validation'],
'max_validation' => $getQuestions_rec['max_validation']
);
}
if(is_array($get_questions_array) && count($get_questions_array)>0)
{
foreach($get_questions_array as $key=>$array)
{
if($array === null) {
unset($get_questions_array[$key]);
}
$return['data']['questions'][] = $array;
}
}
}
else
//error
A return for example; would look like this:
"question_id":"3",
"related_form_id":"4",
"question_body":"Do you like this content?",
"question_type":"radio",
"possible_answer1":"Disagree",
"possible_answer2":"Neutral",
"possible_answer3":"Agree",
"possible_answer4":null,
"possible_answer5":null,
"possible_answer6":null,
"min_validation":"1",
"max_validation":"1"
I've tried unsetting the key using empty and isnull but to no avail. Any help would be appreciated.
You are not testing the values inside the array, you need to:
foreach($get_questions_array as $array){
foreach($array as $key=>$element){
if($element===null)
unset($array[$key]);
}
$return['data']['questions'][] = $array;
}
I think it's possible you're looping through your nested data structure at the wrong level.
You have this $get_questions_array, each element of which is an associative array that came from one row in your MySQL result set. But your php code loops over the rows of the result set, not over the columns.
I think you want something more like this, with another nested foreach.
if(is_array($get_questions_array) && count($get_questions_array)>0)
{
foreach($get_questions_array as $row)
{
foreach ($row AS $colname=>$colvalue)
{
if ($colvalue === null || $colvalue =='')
{
unset($row[$colname]);
}
}
}
}
See what's going on? Your code was throwing away whole rows that were null, but there weren't any of those, so it wasn't doing anything.
why don't you query the data that does not contain nulls, instead of removing the nulls by yourself ? let the database do this for you something like:
select * from table where possible_answer IS NOT NULL
Try this loop through the array and set them to null with the key's if the value is empty
foreach($getQuestions_rec as $key => $value){
if($value == ''){
$getQuestions_rec[$key] = null;
}
}
Use the IFNULL(ColumnName,"") to replace the null values to empty string in SQL query.
Example: IFNULL(answer6,"")
refer this this How to remove null values from an array? or you ca alter the query to select the null values from table.
First, thanks for any help.
I've spent countless hours on here and other forums trying to find my exact solution but either 1) I'm not understanding the one's I've read or 2)I haven't found the right answer.
In PHP, I've run a somewhat complex query which returns a set of records similar to:
id | name | direction|
1 aaa east
2 bbb west
3 ccc east
I've created an associative array such as:
$query=("select * from foo");
$result=mysql_query($query);
$array=mysql_fetch_assoc($result);
Now, what I need to do seems simple but I'm not grasping the concept for some reason.
I need to loop through the entire $array and return a count of any value that I want to specify and store that count in a variable.
i.e. Show me how many times east shows up in the "direction" column and put that in a variable called $eastcount.
I've tried various combinations of using foreach loops with incremental counts and have tried using array_count_values but have not been able to put the pieces together :/
// build query
$query=("select * from foo");
// execute query
$result=mysql_query($query);
// declare vars
$east_count = 0;
// iterate through results
while ($data = mysql_fetch_array($result)) {
// grab DIRECTION column value
$direction = $data['direction'];
// detect 'east'
if ($direction == 'east') {
// increment 'east' count
$east_count++;
}
}
// print # of times we had 'east'
echo("direction said 'east' $east_count times");
This should work (sorry for the lack of code block I'm on my iPhone).
http://www.php.net/manual/en/function.array-count-values.php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
Array
(
[1] => 2
[hello] => 2
[world] => 1
)
How about this:
query=("select * from foo");
$result=mysql_query($query);
$directions = array();
while($direction = mysql_fetch_assoc($result) {
$directions[] = $direction['direction'];
}
$directionCounts = array_count_values($directions);
//now you can access your counts like this:
echo $directionCounts['east'];
First, of all you should be using mysqli instead. But, anyhow I hope this makes some sense.
if ($result) {
$count = 0;
while ( $row = mysql_fetch_assoc($result)) {
if ($row["route"] === "east") {
$count += 1;
}
}
return $count;
}
I have a table like this:
id
name
parent_id
I then want to select certain rows based on their id, so something like this:
SELECT *
FROM TABLE
WHERE id IN ('1', '5', '8', '9', '35')
I want to, from this query, also show the parent/child relationship, like:
id parent
-----------
1 0
5 1
8 0
9 8
35 9
So the final output would look something like this:
1
--5
8
--9
----35
Do I do this outside of mysql, i have tried using arrays, but can't figure it out, or
Do I do it inside MYSQL, which i don't know how to do that either.
Here is what I was able to come with which seems to be working great.
PS-Sorry about the formatting, can't figure it out :( (fixed?)
I grab my parent_id and id from MYSQL and put it into an arraly where the array keys are the id's and the values are the parents, so with in the while loop for mysql, something like this: $testarray[$id] = $parent_id;
Then I run it through the functions below, and it orders it just how I need it.
function retrieveSubTree($parent, $myarray) {
$tempArray = $myarray;
$array = array();
//now we have our top level parent, lets put its children into an array, yea!
while ($child = array_search($parent, $tempArray)) {
unset($tempArray[$child]);
//now lets get all this guys children
if (in_array($child, $tempArray)) {
$array[$child] = retrieveSubTree($child, $tempArray);
} else {
$array[$child] = true;
}
}//end while
return (!empty($array)) ? $array : false;
}
function retrieveTree($myarray) {
$array = array();
$counter = 0;
foreach ($myarray as $key => $value) {
$child = $key;
$parent = $value;
//if this child is a parent of somebody else
if (in_array($child, $myarray) && $parent != '0') {
while ($myarray[$parent] != '' && $myarray[$parent] != '0') {
$newparent = $myarray[$parent];
$parent = $newparent;
}
if (!array_key_exists($parent, $array)) {
$array[$parent] = retrieveSubTree($parent, $myarray);
}
} else {
//now make sure they don't appear as some child
if (!array_key_exists($parent, $myarray)) {
//see if it is a parent of anybody
if (in_array($child, $myarray)) {
$array[$child] = retrieveSubTree($child, $myarray);
} else {
$array[$child] = true;
}
}//end if array key
}//end initial in array
}//end foreach
return (!empty($array) ? $array : false);
}
$test = array(
'1'=>'15',
'2'=>'1',
'3'=>'1',
'4'=>'0',
'5'=>'0',
'6'=>'4',
'7'=>'6',
'8'=>'7',
'9'=>'2',
'10'=>'9'
);
print_r(retrieveTree($test));
Without changing your table structure, this requires recursion, which MySQL does not support. You'll have to do it elsewhere. You can write a recursive function in PHP to use, for example, breadth-first search to build your array. Here it looks like you are using parent_id of 0 to denote a top-level object. You can search over your results, and add to your array every object whose parent is zero, which will give you an array with 1 and 8. Then you can recurse: find all the results with a parent of 1, and add that as a subarray to 1; then find all the results with a parent of 8 and add those as a subarray of 8. Continue doing this for each level until you've run out of results.
As other posters pointed out, you can do this natively in MySQL if you can change the table structure.