Search code examples
phparraysforeachexplode

How would combine multiple exploded lists created by foreach into one array?


Let's say hypothetically I have this information listed on each users profile:

UserA (list) = dog, cat, sheep, bird, duck

UserB (list) = zebra, lion, cheetah, leopard

UserC (list) = alligator, lizard, frog, turtle

and I have this function:

    foreach($users as $user){
       $user_list = $user->list;
       $user_list_array = explode(', ', $user_list);
          foreach($user_list_array as $user_list_item){

          }
       }
    }

This is where I'm stumped... How do I combine all the lists into one big comma separated list and explode that full list into one array that I can then use?


EDIT: Here are the exact sample lists I'm testing with and the results I'm getting with the following code:

THE LISTS:

ListA: Singing, Rapping, Dancing, Comical Skits, Cooking, Cleaning, Shoe-Tying, Hop on No Legs

ListB: Wine Tasting, Hospitality, Business Management, Financial Planning, Business Marketing, Professional Driving

THE CODE:

<?php
$roles = array('employee', 'administrator');
/* Loop through users to search for the admin and employee users. */
foreach( $roles as $role ) {
   $this_role = "'[[:<:]]".$role."[[:>:]]'";
   $query = "SELECT * FROM $wpdb->users WHERE ID = ANY (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = 'wp_capabilities' AND meta_value RLIKE $this_role) ORDER BY user_nicename ASC LIMIT 10000";
   $users = $wpdb->get_results($query);
        if ($users){
        $output = array();
        foreach($users as $user){
                $curuser = get_userdata($user->ID);
                $user_list = $curuser->skills;
                $user_list_array = explode(', ', $user_list);
                foreach($user_list_array as $user_list_item){
                    $output[] = $user_list_item;
                }
            }   
            echo implode(', ', $output);
        }
    }?>

THE RESULT:

Singing, Rapping, Dancing, Comical Skits, Cooking, Cleaning, Shoe-Tying, Hop on No Legs, , , , , , Wine Tasting, Hospitality, Business Management, Financial Planning, Business Marketing, Professional Driving


Solution

  • How do I combine all the lists into one big comma separated list and explode that full list into one array that I can then use?

    That's a long winded process of doing this:

    $output = array();
    foreach($users as $user){
       $user_list = $user->list;
       $user_list_array = explode(', ', $user_list);
       foreach($user_list_array as $user_list_item){
           $output[] = $user_list_item;
       }
    }
    echo implode(', ', $output); // your combined results
    

    But why not simplify it and just concatenate the results you want for each array?

    $output = '';
    foreach($users as $user) {
        $output .= $user->list;
    }
    // this doesn't use arrays at all
    echo $output;
    

    ... or better yet (as far as structured data goes), merge the arrays:

    $output = array();
    foreach($users as $user) {
        $bits = explode(', ', $user->list);
        $output = array_merge($output, $bits);
    }
    
    // this is a simplified step from your first example
    echo implode(', ', $output);
    

    Edit

    Updating based on your output with lots of this: ,,,,,, - chances are you have blank fields in your database. You're still adding those to the array and they're still being comma seperated. I'd suggest this:

    foreach($user_list_array as $user_list_item){
        if(trim($user_list_item) != '')
            $output[] = $user_list_item;
        // only add the item if it's not blank (after trimming potential whitespace off)
    }
    

    Edit : Is there any way to input a comma where the first list stops and next list starts?

    Of course, either add it after the inner foreach loop using the [] structure to add a new array item like this:

    $output[] = PHP_EOL; // or \n newline, or a space, or whatever you want to seperate your sets as well as a comma
    

    ... or the better way (structurally) would be to create a multi dimensional array and implode it at the end;

    $output = array();
    foreach($users as $user){
        $temp_output = array();
        $curuser = get_userdata($user->ID);
        $user_list = $curuser->skills;
        $user_list_array = explode(', ', $user_list);
        foreach($user_list_array as $user_list_item){
            if(trim($user_list_item) != '')
                $temp_output[] = $user_list_item;
        }
        $output[] = implode(', ', $temp_output);
    }
    // put your set delimiter here, whether it's a comma, |, \n, PHP_EOL, whatever
    echo implode(', ', $output);