I've got an array and I need count the keys with a specific value, which is proving to be a nightmare.
Array([0] => Array
(
[0] => 1
[ruleid] => 1
[1] => Test Outbound Life 1
[rule_name] => Test Outbound Life 1
[2] => Life Insurance
[product_type] => Life Insurance
[3] => 1
[status] => 1
[4] => 1000
[priority] => 1000
[5] => 100
[quantity] => 100
[6] => 1-2-3-4-5-6-7-
[dayofweek] => 1-2-3-4-5-6-7-
[7] => 2
[income] => 2
[8] => external/arc.php
[integrationfile] => external/arc.php
[9] => 1
[partnerid] => 1
)
[1] => Array
(
[0] => 2
[ruleid] => 2
[1] => Test Outbound Life 2
[rule_name] => Test Outbound Life 2
[2] => Life Insurance
[product_type] => Life Insurance
[3] => 1
[status] => 1
[4] => 800
[priority] => 800
[5] => 100
[quantity] => 100
[6] => 1-2-3-4-5-6-7-
[dayofweek] => 1-2-3-4-5-6-7-
[7] => 2
[income] => 2
[8] => test.php
[integrationfile] => test.php
[9] => 1
[partnerid] => 1
) )
The array will be generated dynamically so the same array will appear in the array.
I want to count how many times the same ruleid appears is it will look like this:
Array{
[1] => 1
[2] => 1
}
Update: I need to count how many times ruleid = 2 or how many times ruleid = 1
So you want to count the number of time each ruleid appears inside an array.
Let's call this array $count. This is how I'd do it.
$count = array();
foreach($arrays as $array) { // $arrays is your big ass array containing arrays
// increment the value with the key corresponding to ruleid (improved by JustOnUnderMillions)
$count[$array['ruleid']] = isset($count[$array['ruleid']]) ? ($count[$array['ruleid']] + 1) : 1;
}
print_r(count); // should give you what you're looking for
I have worked it out by looping and counting how many times a ruleid appears in an array.
foreach ($count as $key => $value) {
$c = 0;
//check that outbound has passed all rules
foreach ($out as $k => $v) {
if ($v['ruleid']==$key) {
$c +=1;
}
}
if ($c==$value) {
//add valid outbound to array
foreach ($out as $k => $v) {
if ($v['ruleid']==$key) {
$valid[$key] = $v;
}
}
}
}
The loop checks the ruleid has passed all rules I had already counted in the $count variable.
Related
I have this response
[0] => Array (
[name] => Test
[question_id] => 4
[question_choice_id] => 14
[choice_level] => 0
)
[1] => Array (
[name] => Test
[question_id] => 5
[question_choice_id] => 19
[choice_level] => 0
)
[2] => Array (
[name] => Test
[question_id] => 6
[question_choice_id] => 24
[choice_level] => 0
)
[3] => Array (
[name] => Test
[question_id] => 7
[question_choice_id] => 26
[choice_level] => 0
)
[4] => Array (
[name] => Test
[question_id] => 8
[question_choice_id] => 29
[choice_level] => 1
)
[5] => Array (
[name] => Test
[question_id] => 9
[question_choice_id] => 36
[choice_level] => 0
)
[6] => Array (
[name] => Test
[question_id] => 1
[question_choice_id] => 2
[choice_level] => 0
)
[7] => Array (
[name] => Test
[question_id] => 2
[question_choice_id] => 7
[choice_level] => 0
)
[8] => Array (
[name] => Test
[question_id] => 3
[question_choice_id] => 9
[choice_level] => 0
)
I want to get the percentage of the user with the formula of
Score = the_right_answer / total_count_array * 100
The correct answer has a value of 1 in the choice_level columns
so for my example is, the formula should be
Score = 1/ 9 * 100
How can I get the total from this array?
Once I get the answer I just like to return them to my view.
public function progress(){
$category_id = Session::get('category_id');
$user_set_id = Session::get('user_set_id');
$score = Answer::get_user_score($user_set_id,$category_id);
return view('pages.user.user_progress', [
'name' => '',
'score' => '',
]);
}
Can anyone help me on how to do this properly? any help would be really appreciated.
Based on Score = total count_of_array / the_right_answer * 100:
for total count_of_array could be calculated easily using count($answes)
for calculating the_right_answer, you can use array_map() or manual loop:
$total = count($answers);
$correct = 0;
foreach($answers as $answer){
if($answer['choice_level'] == '1'){
$correct++;
}
}
the snippet above will give you $correct as total correct answer
Now that you have the needed data, you can then do the calculation yourself. However, I would remind you that when the user doesn't have any correct answer, you will face a Division by zero warning. Keep that in mind😉
Since apparently choice_level can only take the values 0 or 1 you can use array_sum to get the number of correct answers. You will need to reduce the response array to just that field first, you can achive that with array_column. So all together:
$score = array_sum(array_column($answers, 'choice_level')) / count($answers) * 100;
for each($arrayname['score'] as $item){
}
I need help, tried for days without successs, new to PHP so please forgive me, I have an associative Array below returned from a database table grading system, what I want to achieve is try "scores" from another associative array, iterate through the grading system until I find a score that falls between values in a row in the grading system then return the letter grade and remarks, see below what have tried, am exhausted, any help would be very appreciated.
code I have tried
while ($row = $grade->fetch(PDO::FETCH_ASSOC)) {
$data = $row;
var_export($data);
} //fetches the grading system whose array is seen below
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$scores = $row;
var_export($scores);
}// fetches scores of students in test
foreach($data as $key=> $grading) {
foreach($scores as $key =>$values){
if($values["marks"]>=$grading["grade_min"] && $values["marks"]<=$grading["grade_max"])
print_r($values["marks"]);
print_r($grading["grade"]);
print_r($grading["remarks"]);
}
} Am trying to iterate each scores against the grading system but not successful, please help.
Array
(
[0] => Array
(
[id] => 2
[grade_min] => 1
[grade_max] => 39
[grade] => E
[remarks] => Fail
)
[1] => Array
(
[id] => 3
[grade_min] => 40
[grade_max] => 49
[grade] => D
[remarks] => Pass
)
[2] => Array
(
[id] => 4
[grade_min] => 50
[grade_max] => 59
[grade] => C
[remarks] => Credit
)
[3] => Array
(
[id] => 5
[grade_min] => 60
[grade_max] => 69
[grade] => B
[remarks] => Good
)
[4] => Array
(
[id] => 6
[grade_min] => 70
[grade_max] => 79
[grade] => A
[remarks] => Very Good
)
[5] => Array
(
[id] => 7
[grade_min] => 80
[grade_max] => 100
[grade] => A+
[remarks] => Excellent
)
)
Array
(
[0] => Array
(
[id] => 2
[grade_min] => 1
[grade_max] => 39
[grade] => E
[remarks] => Fail
)
[1] => Array
(
[id] => 3
[grade_min] => 40
[grade_max] => 49
[grade] => D
[remarks] => Pass
)
[2] => Array
(
[id] => 4
[grade_min] => 50
[grade_max] => 59
[grade] => C
[remarks] => Credit
)
[3] => Array
(
[id] => 5
[grade_min] => 60
[grade_max] => 69
[grade] => B
[remarks] => Good
)
[4] => Array
(
[id] => 6
[grade_min] => 70
[grade_max] => 79
[grade] => A
[remarks] => Very Good
)
[5] => Array
(
[id] => 7
[grade_min] => 80
[grade_max] => 100
[grade] => A+
[remarks] => Excellent
)
)
Scores Array looks like this:
Array
(
[0] => 35
[1] => 48
[2] => 57
[3] => 78
[4] => 75
[5] => 89
)
I want to iterate these scores array against the grading system array and return only the "grade" and "remarks" that matched where the scores is between "grade_min" and "grade_max"
It's better to iterate over scores and then iterate grading to find the one that score belongs to.
Additionally, your if has no curly braces, so it will execute only the first sentence after it.
// fetches the grading system whose array is seen below
while ($row = $grade->fetch(PDO::FETCH_ASSOC)) {
$data = $row;
// var_export($data); // No need to se this anymore
}
// fetches scores of students in test
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$scores = $row;
// var_export($scores); // No need to see this anymore
}
// Iterate scores first (I don't know if you need the index or not)
foreach($scores as $scoreIndex => $score) {
// Search grading for this score (Index not needed here, just values)
foreach($data as $grading) {
if($score['marks'] >= $grading['grade_min'] && $score['marks'] <= $grading['grade_max']) {
// Score is inside this grading
// Echo, print or assign what you need here
// Then exit the loop for grading
break;
}
}
}
Based on your output for $scores, that array is just a single value, no associative array, so the loop should be:
// Iterate scores first (I don't know if you need the index or not)
foreach($scores as $scoreIndex => $score) {
// Search grading for this score (Index not needed here, just values)
foreach($data as $grading) {
// $score is an integer, not an array
if($score >= $grading['grade_min'] && $score <= $grading['grade_max']) {
// Score is inside this grading
// Echo here what you need
// Then exit the loop for grading
break;
}
}
}
I have tried doing this for a while and can't wrap my head around it. I have two arrays. One array that contains sensors information called $sendatas and another that contains where those sensors are allocated to called $zones.
I want to be able to create dynamic HTML checkboxes within a table row based on whether the sensor is allocated to a zone or not and if it is then show a checked checkbox and if it isn't then show an unchecked checkbox.
Here is an example of my arrays:
The $sendatas array:
[1] => Array
(
[hwserial] => 00002025
[name] => FG05 Room Temp
[serial] => 5
[chan] => 1
[alarmhigh] => 30
[alarmlow] => 5
[delay] => 10
)
[2] => Array
(
[hwserial] => 00002025 01
[name] => FG05 Kitchen 1 Freezer
[serial] => 5
[chan] => 2
[alarmhigh] => -10
[alarmlow] => -35
[delay] => 10
)
The $zones array:
[0] => Array
(
[serial] => 1
[idGrid] => 50
[name] => All Sensors
)
[1] => Array
(
[serial] => 1
[idGrid] => 52
[name] => Food Area
)
[2] => Array
(
[serial] => 2
[idGrid] => 50
[name] => All Sensors
)
[3] => Array
(
[serial] => 2
[idGrid] => 52
[name] => Food Area
)
[4] => Array
(
[serial] => 3
[idGrid] => 50
[name] => All Sensors
)
[5] => Array
(
[serial] => 3
[idGrid] => 52
[name] => Food Area
)
[6] => Array
(
[serial] => 4
[idGrid] => 50
[name] => All Sensors
)
Both of my zones are not the same length. What I want to be able to achieve is to create an array that looks like this by finding the serial keys that match from both arrays.
Array
(
[0] => Array
(
[hwserial] => 00001216
[name] => Fridge Office Thermal
[serial] => 1
[chan] => 1
[alarmhigh] => 8
[alarmlow] => -2
[delay] => 10
[idGrid1] => 50
[idGrid2] => 51
[idGrid3] => 52
[zonename1] => All Sensors
[zonename2] => Office
[zonename3] => Food Area
)
[1] => Array
(
[hwserial] => 00002025
[name] => FG05 Room Temp
[serial] => 5
[chan] => 1
[alarmhigh] => 30
[alarmlow] => 5
[delay] => 10
[idGrid] => 50
[idGrid] => Not Used
[idGrid] => 52
[zonename1] => All Sensors
[zonename2] => Not Used
[zonename3] => Food Area
)
I am pretty sure I can write the code for the checkboxes once I have this array formatted properly. I have tried using some foreach loops but just keep making a mess of it. I have so far tried this on and off for a few weeks hoping it would just come to me but it hasn't. Any help appreciated.
Based on what you said you're trying to do with this, I think it looks like the array you're trying to create will not be that easy to work with. I think your sensors array is fine, and you just need to focus on the $zones array.
foreach ($zones as $zone) {
$zones_sensors[$zone['idGrid']]['name'] = $zone['name'];
$zones_sensors[$zone['idGrid']]['sensors'][$zone['serial']] = true;
}
This will reorganize the data in your $zones array into this format:
$zones_sensors = [
50 => ['name' => 'All Sensors', 'sensors' => [1 => true, 2 => true, 3 => true]],
51 => ['name' => 'Office', 'sensors' => [1 => true]],
52 => ['name' => 'Food Area', 'sensors' => [1 => true, 2 => true, 3 => true]]
];
This provides the two things you need to output the checkboxes as you described.
A complete list of zones
An indexed collection of serials associated with each zone.
You can use it to output headers for all the zones
foreach ($zones_sensors as $zone_id => $zone) {
// output one row with headers for zones
echo $zone['name']; // (formatting up to you)
}
Then when you output the sensors it will be easy to find which zones they're allocated to.
foreach ($sendatas as $sensor) { // make a row for each sensor
foreach ($zones_sensors as $zone_id => $zone) { // iterate the full list of zones
// check if the sensor is allocated to that zone
if (isset($zone['sensors'][$sensor['serial']])) {
// checkbox is checked
} else {
// checkbox is unchecked
}
}
}
This should just be a matter of creating a new array (let's call it $combined) that is a clone of one of the $sendatas array but uses the [serial] as a key so that you can target specific item. You would loop through the $zones array and for each item check if the [serial] is found in $combo and if a match is found inject the [idgrid] and [name] as a sub array for $combined['serial']. As you have not used sub array you could add a counter to add an incrementing number of values.
Something along the lines of this should do the trick:
$results = [];
foreach ($sendatas as $sensor) {
$zone_counter = 0;
foreach ($zones as $zone) {
if ($zone['serial'] == $sensor['serial']) {
$zone_counter++;
$sensor['idGrid' . $zone_counter] = $zone['idGrid'];
$sensor['zonename' . $zone_counter] = $zone['name'];
}
}
$results[] = $sensor;
// if you only want $results to contain sensors that actually have zones,
// wrap it in an if-statement:
// if ($zone_counter > 0) {
// $results[] = $sensor;
// }
}
print_r($results);
Note that this won't give you any sensors with matching zones with the data you provided, because those two sensors both have [serial] => 5 and all your zones have [serial] => 1 through 4. If you want to match by some other key instead of serial, just change the if-statement.
I'm fairly new to PHP and trying to sort a class project. I've banged away and can't see to sort it out, this is the last remaining piece.
I have a form - submit essentially 2 arrays I'm trying to determine the average score for based upon the category groupings. 1. ($_post['category']), ($_post['score']) - with category being a text based array and score obviously being numbers based.
How would I go about finding the average score for each category? I've tried various options to for mapping the two arrays and then trying to average the grades. I can get the total score average pretty easily, but finding a ways to do this by each category individually is tripping me up.
I need to apply a weight to each category score, but that seems pretty easy once you get the above sorted.
Thanks,
Steve
$_POST example:
Array (
[0] => Assignment
[1] => Assignment
[2] => Assignment
[3] => Assignment
[4] => Assignment
[5] => Assignment
[6] => Exam
[7] => Assignment
[8] => Assignment
[9] => Assignment
[10] => Exam
[11] => Exam
[12] => Final Project
)
Array (
[0] => 100
[1] => 100
[2] => 100
[3] => 98
[4] => 90
[5] => 92
[6] => 100
[7] => 100
[8] => 100
[9] => 100
[10] => 100
[11] => 92
[12] => 100
)
There are several ways to go about this, here's one:
// create arrays
$cat = array(
"Assignment", "Assignment", "Assignment",
"Assignment", "Assignment", "Assignment",
"Exam", "Assignment", "Assignment",
"Assignment", "Exam", "Exam", "Final Project");
$grade = array(100,100,100,98,90,92,100,100,100,100,100,92,100);
// create $result: key = cat, values = sum, count, avg = 0
$result = array_fill_keys($cat, array('sum' => 0, 'count' => 0, 'avg' => 0));
$max = count($cat);
// add grades to category in $result[cat][sum]
for ($i = 0; $i < $max; $i++)
$result[$cat[$i]]['sum'] += $grade[$i];
// count number of categories in $cat
$num = array_count_values($cat);
// fill $result[cat][count]...
// then divide each cat's sum by each cat's count => $result[cat][avg]
foreach ($result as $k => $v) {
$result[$k]['count'] = $num[$k];
$result[$k]['avg'] = round($result[$k]['sum'] / $num[$k], 2);
}
Result:
Array
(
[Assignment] => Array
(
[sum] => 880
[count] => 9
[avg] => 97.78
)
[Exam] => Array
(
[sum] => 292
[count] => 3
[avg] => 97.33
)
[Final Project] => Array
(
[sum] => 100
[count] => 1
[avg] => 100
)
)
see it working: http://codepad.viper-7.com/QQAaXD
I am currently stumped while searching for an answer, but I have an array which contains information relating to a tournament, as seen below.
I would like to search through this Array of arrays for specifically the opponent key, and determine if they are all -2. This is because the logic is that -2 is a bye, so if all people have -2 as their opponent, this means that all brackets have been finished.
My initial thought was just do an array_search(!(-2), $anArray), but that obviously didn't work and I hit myself on the head for thinking it would be that easy haha. Thanks.
EX:
Array (
[0] => Array ( [dId] => 11 [uId] => 3 [id] => 1 [round] => 0 [opponent] => 3 [bracket] => 0 )
[1] => Array ( [dId] => 11 [uId] => 5 [id] => 2 [round] => 0 [opponent] => -2 [bracket] => 1 )
[2] => Array ( [dId] => 11 [uId] => 10 [id] => 3 [round] => 0 [opponent] => 1 [bracket] => 0 ) )
This function will return true if all opponents are -2 and false if there is a single opponent != -2:
function all_opponent_search($arr){
for($i = 0; $i < count($arr); $i++)
if($arr[$i]['opponent'] != -2)
return false;
return true;
}
how about:
foreach ($masterArray as $subArray) {
if (isset($subArray['opponent']) && ($subArray['opponent'] == -2)) {
// do whatever you need
}
}