We help IT Professionals succeed at work.
Private
Troubleshooting Question

PHP - Wordpress - Challenges finding and comparing values in nested arrays.

Chris Inman
Chris Inman asked
on
30 Views
Last Modified: 2020-10-23
Hi and thanks for reading. I'm a moderately experienced Wordpress / PHP dev. But this is hard for me and have spent 3 days now trying to figure it out.

Making a time sheet with employees listed and in/out for everyday of the week. I am pulling an ACF repeater row of employees from another page that the employees originally get added. With a while loop, I’m adding employees into a new array ($settings_names) with more fields i.e. Monday In, Monday out etc. Then for each of the users in the array, I’m printing the Agent name as well as Input fields representing the new data fields.
First issue is; the array works great on the first go around (page load) and displays fine and without changing any in/out fields, it saves as an array into wp_post_meta. For dev purposes, the update_post_meta just runs after the page prints just to load the db with the array of data. On subsequent page loads, since the array is saved, it pulls that array and checks against the employee names to see if there are any new ones, if not, it should just continue to print the page and fields with the data pulled from the database.
That first issue is that this sort of works, but not. I seem to get a different array back from the DB with one extra level of array wrapping the main array. This causes some weird duplicated data and the page doesn’t print right.

Second Issue;  Now I need to be able to enter times in those IN/OUT input fields and have them all save back to an array that can be used to update_post_meta. Next time the user comes back and loads the page, they should be able to se the previously inputed times, enter more time data and save again into the array. How do I get these individual rows of time data to save back into the array where they need to be, with each employee?

Third Issue;  The fields are within Form tags and I have a submit button, but not sure how to do the update_post_meta so that the inputs are saved.

I’m aware this is an elephant to be chewed on one bite at a time. So for now any help with the first issue is appreciated.

I am going to post the whole page of code as it is now. Please understand there is still a lot of troubleshooting code in there as well

Thanks for the help.
~ Chris

<?php
/**
 * The template for displaying all single posts.
 *
 */

//if( is_super_admin() || (is_user_logged_in() && (in_array('payroll',$user_info->roles))) ) {

$url = "//$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
get_header();

while ( have_posts() ) : the_post(); //start loop

     $category = get_the_category();
     $title = get_the_title();
     $settings_id = get_id_by_slug('settings') ;
     $timezone = get_field('time_zone' , $settings_id);
     $timeoffset = get_field('time_offset' , $settings_id);
     $timereset = get_field('time_reset' , $settings_id);
     $post_ID = get_the_ID();
     $settings_names = get_post_meta( $post_ID, 'settings_names'); // This is an array that simply holds on to a list of named agents already pulled from settings
//    var_dump($settings_names); die;
     if(!isset($settings_names)):$settings_names = array() ;// If the array has not been created yet, set the variable as an array
         endif;
    var_dump($settings_names);
//    die;

        if( is_user_logged_in() ){
            global $current_user;
            wp_get_current_user();
            $user_info = get_userdata($current_user->ID);
        }

        if( is_super_admin() || (is_user_logged_in() && in_array('operations',$user_info->roles)) ) {
            global $current_user;
            wp_get_current_user();
?>
        <div id="timesheet">
                <div id="content" role="main">
                    <p>Timesheet for : --> <?php echo get_the_title(); ?></p>

                    <form action="/wp-content/themes/czar/timesheet.php" method="post"  class="sales_form_two" style='display:inline' autocomplete="off">
<!--                    <form action="" method="POST"  class="sales_form_two" style='display:inline' autocomplete="off">-->
<!--                    <form action="--><?php //echo $url; ?><!--" method="post"  class="sales_form_two" style='display:inline' autocomplete="off">-->
<!--                    <form action="--><?php //echo $_SERVER['PHP_SELF']; ?><!--" method="post"  class="sales_form_two" style='display:inline' autocomplete="off">-->

<?php    // Get names form the agent_openers list on the settings page and add to an array that will be saved with the post in order to keep track of
        // what has been found and add to it if new entries are made.
            if( have_rows('agents_openers', $settings_id) ):
//                $i = 0;
                while ( have_rows('agents_openers', $settings_id) ) : the_row();
                    if (!get_sub_field('exempt')) { // If the exempt field is true then skip, we don't want to add this agent to the timesheet
                        $pay_name = get_sub_field('agent_name');
// If not already set, set default values and create new agent-named array
                        if (!in_array($pay_name, $settings_names)) { //create an array of names to save for future time sheet editing. only add new Settings page Agent entries
                            $settings_names[$pay_name] = array(
                                'name' => $pay_name,
                                'mon_in' => '9:00am',
                                'mon_out' => 0,
                                'tues_in' => 0,
                                'tues_out' => 0,
                                'wed_in' => 0,
                                'wed_out' => 0,
                                'thurs_in' => 0,
                                'thurs_out' => 0,
                                'fri_in' => 0,
                                'fri_out' => 0,
                                'sat_in' => 0,
                                'sat_out' => 0,
                                'sun_in' => 0,
                                'sun_out' => 0,
//                                'mon_in' => '',
//                                'mon_out' => '',
//                                'tues_in' => '',
//                                'tues_out' => '',
//                                'wed_in' => '',
//                                'wed_out' => '',
//                                'thurs_in' => '',
//                                'thurs_out' => '',
//                                'fri_in' => '',
//                                'fri_out' => '',
//                                'sat_in' => '',
//                                'sat_out' => '',
//                                'sun_in' => '',
//                                'sun_out' => '',
                                'ot_total' => 0,
                                'reg_total' => 0,
                            );
                        } else {
                            continue;
                        }

//                        $i++;
                    }else {
                        continue;
                    }
                endwhile;
            endif;
//var_dump($settings_names);

//            update_post_meta($post_ID, 'settings_names',$settings_names);
//die;

// get post_meta of current array fields if they already exist
//        $settings_names = get_post_meta($post_ID, 'settings_names');

//        print_r($settings_names1);
//        var_dump($settings_names);
//        die;

        $html = '<div class="pay_flex">';
        $html .= '<span class="pay_week">   Monday  </span><span class="pay_week">  Tuesday  </span><span class="pay_week"> Wednesday </span><span class="pay_week"> Thursday  </span><span class="pay_week">   Friday  </span><span class="pay_week"> Saturday  </span><span class="pay_week">   Sunday  </span></div>';
        $html .= '<div class="pay_detail">';
        if (isset($settings_names)) {
            $i=0;
            //Use the below for straight through code - not going to the DB first
            foreach( $settings_names as $user ){  // $user is formerly $pay_name when first created

                // Use the below if pulling out from DB
//            foreach( $settings_names[$i] as $user ){  // $user is formerly $pay_name when first created

                $pay_name1[$i] = $user['name'];
                $mon_in[$i] = $user['mon_in'];
                $mon_out[$i] = $user['mon_out'];
                $tues_in[$i] = $user['tues_in'];
                $tues_out[$i] = $user['tues_out'];
                $wed_in[$i] = $user['wed_in'];
                $wed_out[$i] = $user['wed_out'];
                $thurs_in[$i] = $user['thurs_in'];
                $thurs_out[$i] = $user['thurs_out'];
                $fri_in[$i] = $user['fri_in'];
                $fri_out[$i] = $user['fri_out'];
                $sat_in[$i] = $user['sat_in'];
                $sat_out[$i] = $user['sat_out'];
                $sun_in[$i] = $user['sun_in'];
                $sun_out[$i] = $user['sun_out'];
                $reg_total[$i] = $user['reg_total'];
                $ot_total[$i] = $user['ot_total'];
// Display data in rows with Entry fields and labels
                $html .= '<p><span class="name_space">'.$pay_name1[$i].'</span>' ;
                $html .= '<input type="text" class="time_input" name="mon_in" placeholder="IN" value="'. $mon_in[$i] .'" onfocus="if(this.value == \'\') { this.value = \'\'; }" onblur="if(this.value == \'\') { this.value = \'\'; }">';
                $html .= '<input type="text" class="time_input" name="mon_out" placeholder="OUT" value="'. $mon_out[$i] .'" onfocus="if(this.value == \'\') { this.value = \'\'; }" onblur="if(this.value == \'\') { this.value = \'\'; }" style="margin-right: 5px" >';
                $html .= '<input type="text" class="time_input" name="tues_in" placeholder="IN" value="'. $tues_in[$i] .'" onfocus="if(this.value == \'\') { this.value = \'\'; }" onblur="if(this.value == \'\') { this.value = \'\'; }" >';
                $html .= '<input type="text" class="time_input" name="tues_out" placeholder="OUT" value="'. $tues_out[$i] .'" onfocus="if(this.value == \'\') { this.value = \'\'; }" onblur="if(this.value == \'\') { this.value = \'\'; }" style="margin-right: 5px" >';
                $html .= '<input type="text" class="time_input" name="wed_in" placeholder="IN" value="'. $wed_in[$i] .'" onfocus="if(this.value == \'\') { this.value = \'\'; }" onblur="if(this.value == \'\') { this.value = \'\'; }" >';
                $html .= '<input type="text" class="time_input" name="wed_out" placeholder="OUT" value="'. $wed_out[$i] .'" onfocus="if(this.value == \'\') { this.value = \'\'; }" onblur="if(this.value == \'\') { this.value = \'\'; }" style="margin-right: 5px" >';
                $html .= '<input type="text" class="time_input" name="thurs_in" placeholder="IN" value="'. $thurs_in[$i] .'" onfocus="if(this.value == \'\') { this.value = \'\'; }" onblur="if(this.value == \'\') { this.value = \'\'; }" >';
                $html .= '<input type="text" class="time_input" name="thurs_out" placeholder="OUT" value="'. $thurs_out[$i] .'" onfocus="if(this.value == \'\') { this.value = \'\'; }" onblur="if(this.value == \'\') { this.value = \'\'; }" style="margin-right: 5px" >';
                $html .= '<input type="text" class="time_input" name="fri_in" placeholder="IN" value="'. $fri_in[$i] .'" onfocus="if(this.value == \'\') { this.value = \'\'; }" onblur="if(this.value == \'\') { this.value = \'\'; }" >';
                $html .= '<input type="text" class="time_input" name="fri_out" placeholder="OUT" value="'. $fri_out[$i] .'" onfocus="if(this.value == \'\') { this.value = \'\'; }" onblur="if(this.value == \'\') { this.value = \'\'; }" style="margin-right: 5px" >';
                $html .= '<input type="text" class="time_input" name="sat_in" placeholder="IN" value="'. $sat_in[$i] .'" onfocus="if(this.value == \'\') { this.value = \'\'; }" onblur="if(this.value == \'\') { this.value = \'\'; }" >';
                $html .= '<input type="text" class="time_input" name="sat_out" placeholder="OUT" value="'. $sat_out[$i] .'" onfocus="if(this.value == \'\') { this.value = \'\'; }" onblur="if(this.value == \'\') { this.value = \'\'; }" style="margin-right: 5px" >';
                $html .= '<input type="text" class="time_input" name="sun_in" placeholder="IN" value="'. $sun_in[$i] .'" onfocus="if(this.value == \'\') { this.value = \'\'; }" onblur="if(this.value == \'\') { this.value = \'\'; }" >';
                $html .= '<input type="text" class="time_input" name="sun_out" placeholder="OUT" value="'. $sun_out[$i] .'" onfocus="if(this.value == \'\') { this.value = \'\'; }" onblur="if(this.value == \'\') { this.value = \'\'; }" ></p>';

                $i++;
            }

        }
        $html .='</div>';
echo $html; // Collective HTMl is printed to screen

//Javascript will create totals and add to arrays total and ot total fields

// Run a loop from the above and add the data back into the array with updated time fields
//                    Foreach row of user as long as their is length of user rows
//                    Write each user row with new time fields back to the array


//Submit button will wrap up the arrays of data and save back to post_meta for each name
?>
<!--                <div class="change_l" style="float:left;"><a href="#"><input type="submit" value="Submit" id="timesheet_submit" class="chone" style="margin-top:15px;margin-right:10px;"></a></div>-->
                <div class="change_l" style="float:left;"><a href="#"><input type="submit" value="Submit" class="chone" style="margin-top:15px;margin-right:10px;"></a></div>
<?php

var_dump($settings_names);

//            update_post_meta($post_ID, 'settings_names',$settings_names);


?>
                    </form>
                </div><!-- #content -->
            </div><!-- #timesheet -->
        <?php
        } elseif( is_user_logged_in() && (!in_array('operations',$user_info->roles)) ){
            echo '<div id="message_alert">You do not have permission to view this page.</div>';
        } else{
            echo '<div id="message_alert">You must be logged in to view this page.</div>';
        }

endwhile; // end of the loop?>
<?php
get_footer();



Comment
Watch Question

Chris InmanIT Admin and sometimes Web Dude

Author

Commented:
First array looks good on first page load with no data saved into DB. Notice array depth.

Then on second round, the array looks like it gets deeper and I don't know if I'm addressing the correct depth in the code, or if this is anything at all.
Chris InmanIT Admin and sometimes Web Dude

Author

Commented:
I am not opposed to scraping this whole code and doing it a different way as long as the inputs (Employee names), tabular in/out data entry and outputs (Daily hours associated with names) ends up the same.
Maybe I need to see if I can add each employee to their own post_meta array with hours, instead of all going into one array? HELP
Chris InmanIT Admin and sometimes Web Dude

Author

Commented:
I might be going in a different direction and instead of stuffing all the employees and data into one array, I'm creating a separate post_meta array for each employee. So far this is giving me more stable meta_data returns on page reloads and it looks as expected. Now I just need to see if this pans out for the rest of the code. Not sure how I'm going to be able to grab each post_meta with names as keys to display rows of data entry yet. Here's new code so far:
<?php
/**
 * The template for displaying all single posts.
 *
 */

//if( is_super_admin() || (is_user_logged_in() && (in_array('payroll',$user_info->roles))) ) {

$url = "//$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
get_header();

while ( have_posts() ) : the_post(); //start loop

    $settings_id = get_id_by_slug('settings') ;
    $post_ID = get_the_ID();

    $post_meta = get_post_meta( $post_ID); // This is an array that simply holds on to a list of named agents already pulled from settings

    var_dump($post_meta);
// die;

//    if(!isset($settings_names)):$settings_names = array() ;// If the array has not been created yet, set the variable as an array
//    endif;

    if( have_rows('agents_openers', $settings_id) ):
        while ( have_rows('agents_openers', $settings_id) ) : the_row();
            if (!get_sub_field('exempt')) { // If the exempt field is true then skip, we don't want to add this agent to the timesheet
                $pay_name = get_sub_field('agent_name');
                // If not already set, set default values and create new agent-named array
                if (!in_array($pay_name, $post_meta)) { //create an array of names to save for future time sheet editing. only add new Settings page Agent entries
                    $settings_names[$pay_name] = array(  // Works creating named arrays with name key / value pairs
//                    array_push($settings_names[$pay_name],$pay_name);
//                    $name = 'name';
//                    array_push($settings_names , $name = $pay_name) ;
//                    array_push($settings_names[name] = $pay_name)); // works
//                    $settings_names = array(
                        'name' => $pay_name,
                        'mon_in' => '9:00am',
                        'mon_out' => 0,
                        'tues_in' => 0,
                        'tues_out' => 0,
                        'wed_in' => 0,
                        'wed_out' => 0,
                        'thurs_in' => 0,
                        'thurs_out' => 0,
                        'fri_in' => 0,
                        'fri_out' => 0,
                        'sat_in' => 0,
                        'sat_out' => 0,
                        'sun_in' => 0,
                        'sun_out' => 0,
                        'ot_total' => 0,
                        'reg_total' => 0,

                    );

                } else {
                    continue;
                }

            }else {
                continue;
            }
        endwhile;
    endif;

    var_dump($settings_names);
//die;
        foreach ($settings_names as $names){
            $name2 = $names['name'];
            $settings = array(
            'pay_name1' => $names['name'],
            'mon_in' => $names['mon_in'],
            'mon_out' => $names['mon_out'],
            'tues_in' => $names['tues_in'],
            'tues_out' => $names['tues_out'],
            'wed_in' => $names['wed_in'],
            'wed_out' => $names['wed_out'],
            'thurs_in' => $names['thurs_in'],
            'thurs_out' => $names['thurs_out'],
            'fri_in' => $names['fri_in'],
            'fri_out' => $names['fri_out'],
            'sat_in' => $names['sat_in'],
            'sat_out' => $names['sat_out'],
            'sun_in' => $names['sun_in'],
            'sun_out' => $names['sun_out'],
            'reg_total' => $names['reg_total'],
            'ot_total' => $names['ot_total']

            );

            update_post_meta($post_ID, $name2 ,$settings);
        }

//    var_dump($settings_names);
    die;
IT Admin and sometimes Web Dude
Commented:
This problem has been solved!
(Unlock this solution with a 7-day Free Trial)
UNLOCK SOLUTION

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions