0

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

4
  • Is this a pseudo-algorithm or are you asking about a specific language? And what is the expected result? Is "explode" a library function? Commented Dec 14, 2013 at 21:39
  • Sorry to be so vague. This is just a generic example of what I'm trying to do in Wordpress where it queries SQL for the "list" meta value for each user. I want to combine all user's lists into one big array of individual "tags" that I can use. Commented Dec 14, 2013 at 22:00
  • My first piece of advice is to not make iterated queries. Commented Jun 15, 2022 at 4:06
  • Just like you do with $users, you just need to check if $user_list is non-empty. Commented Jun 15, 2022 at 4:14

4 Answers 4

1

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);
Sign up to request clarification or add additional context in comments.

5 Comments

I've edited my question so you could see what's occurring... I'm getting this weird case where the commas are all inserted in between the two lists.
That worked!..but one thing. Is there any way to input a comma where the first list stops and next list starts?
PERFECT! Problem solved! Thank you very much for your time/help. Now on to the next phase of my project. You're the man @scrowler!
@Kubashi - no worries - accept :) You'll get a medal for it too
Accepted! Sorry, I'm just getting the hang of this tool. Thanks again!
0
$bigArray = array();
foreach($users as $user){
    $user_list = $user->list;
    $user_list_array = explode(', ', $user_list);
    foreach($user_list_array as $user_list_item){
        $bigArray[] = $user_list_item;
    }
}

Comments

0
$all_user_list_array = array();
foreach($users as $user){
   $user_list = $user->list;
   $user_list_array = explode(', ', $user_list);
   $all_user_list_array = array_merge($all_user_list_array, $user_list_array); 
}

$all_user_list = implode(', ', $all_user_list_array);

I'm basically creating one big array of all the list items and then packing it down in to an array, splitting each value by a comma.

It might be worth asking exactly what you are trying to achieve? There are better ways of storing data than comma separated strings. These string can take a while to process as they need to be tokenised. However, I appreciate you may have your own use cases.

4 Comments

It's comma separated because it comes from a form that asks about the user's skills. It asks them to enter each skill separated by comma.
That's fair enough, but that doesn't mean you need to store it like that. It might be nicer to split the values upon submission in to an array and assign them to the user. In that case it will help you later down the line. For example if the user wants to edit the list and remove an item. It becomes much simpler to add that feature if the values are stored in an array.
Sorry I've never used Gravity Forms. If you post some example code I can try and help you if you have any issues.
Thanks... I'll see if I can get something started.
0

This will give you a complete list with unique values (no duplicates from mulitple lists). I assumed that with UserA (list) you have an array of users with a user object.

$complete_list = array();

foreach( $users as $user )
{
    $list = explode( ",", $user->list );
    foreach( $list as $k=>$item ) $list[$k] = trim( $item );
    $complete_list = array_merge( $complete_list, $list );
}

If your users array is an array, this is the solution:

$complete_list = array();

foreach( $users as $user )
{
    $list = explode( ",", $user['list'] );
    foreach( $list as $k=>$item ) $list[$k] = trim( $item );
    $complete_list = array_merge( $complete_list, $list );
}

2 Comments

@Kubashi - trim removes whitespace on the left and right ends of a string
The array_merge gives you the unique values... trim just removes whitespace. Looking at it now... that won't work the way I have it... I'll fix it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.