Search code examples
phpsqlarraysassociative-array

Loop and store key value from associative array in PHP


I'm trying to extract values from a PHP associative array I have created from an SQL query

SELECT WEEKDAY(Date) AS weekday, 100 * SUM(Att_Type) / COUNT(Att_Type) AS percentage 
FROM Attendance 
WHERE ID=$ID AND WEEK(Date) = WEEK(NOW()) 
GROUP BY WEEKDAY(Date)

which is being stored in the variable $arr with the contents I have found using the print_r command:

Array ( [weekday] => 2 [percentage] => 100.0000 ) 
Array ( [weekday] => 1 [percentage] => 100.0000 ) 
Array ( [weekday] => 0 [percentage] => 66.6667 ) 
Array ( [weekday] => 3 [percentage] => 100.0000 )

I'm new to PHP associative arrays and I was wondering how I could create a function where it will take the value of the weekday key, if it is 0 (Monday), store the value of the percentage key in the Monday variable and so on for the rest of the weekday values available up to 4 (Friday).

EDIT:

The output I am looking for is where the values are saved to independent variables so when called they plainly display the value such as:

$monday = 66.6667
$tuesday = 100.0000
$wednesday = 100.0000
$thursday = 100.0000
$friday = 0 //when there is no value corresponding to that weekday in the array then it will be 0

so they can be echoed later in the code.


Solution

  • $data = [['weekday' => 2, 'percentage' => 100.0000,], ['weekday' => 1, 'percentage' => 100.0000,], ['weekday' => 0, 'percentage' => 66.6667,], ['weekday' => 3, 'percentage' => 100.0000,]];    
    
    $days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
    
    foreach ($days as $day) {
        ${$day} = 0;
    }
    

    If you're using $results = mysqli_fetch_all($result, MYSQLI_ASSOC) to get the array of the results use this;

    $results = mysqli_fetch_all($result, MYSQLI_ASSOC);
    
    foreach($results as $arr) {
        ${$days[$arr['weekday']]} = $arr['percentage'];
        // $arr['weekday'] gets the weekday of the array;
        // $days[$arr['weekday']] gets the day index from the days array
        // ${$days[$arr['weekday']]} then creates a variable with the particular weekday as the variable name
    }
    

    Or if you're using while ($arr = mysqli_fetch_assoc($result))

    while ($arr = mysqli_fetch_assoc($result)) {
        ${$days[$arr['weekday']]} = $arr['percentage'];
    }