1

I have a table that has a column with data stored as comma-separated strings.

I need to output the table contents and build an array from these values (don't need any keys).

I need to remove duplicates and sort it in alphabetical order.

$arr = array();

foreach ($myTable AS $t) {
    $str = $t->myStr;
    array_push($arr, $str);
} 

array_unique($arr);
asort($arr);

I did print_r($arr); Now I see values but they are still an array of strings. Something like this:

Array ( [1] => Chinese, Asian Fusion, Food Trucks [0] => Chinese, Asian Fusion, Gluten-Free [2] => Chinese, Barbeque [3] => Dim Sum, Seafood, Soup )

What I would like to see is:

Array ('Asian Fusion', 'Barbeque', 'Chinese', 'Food Trucks', 'Gluten-Free'...);

3
  • 2
    1) Please add a little example with some data what you have and in which form do you want to get it? (multidimensional array, one dimensional array, ...) 2) array_unique() should be reassigned to $arr Commented Mar 6, 2016 at 17:41
  • 3
    Besides from @Rizier123's comment on array_unique, there is no attempt to output anything in your code. Please, take a look at print_r: use it like so print_r($arr); Commented Mar 6, 2016 at 17:41
  • updated original post Commented Mar 6, 2016 at 17:52

2 Answers 2

3

You have to change this line:

array_push( $arr, $str );

in:

$arr = array_merge( $arr, explode( ',', $str) );

and this:

array_unique( $arr );

in:

$arr = array_unique( $arr );

array_push() add the comma-separated string to the array. Using explode() you obtain an array with single values, then you have to merge this array with main array. You can't use array_push() with exploded array, because using it you will obtain a multidimensional array ( [ [Chinese,Asian,...] , [Chinese,Asian,...] ] ).

array_unique() doesn't change the original array, but it return the modified array, so you have to catch the result in a variable.

Edit:

The delimiter must be the complete separation string.
So, if your string is like this:

Chinese, Asian Fusion, Food Trucks
        ^             ^

you have to use:

$arr = array_merge( $arr, explode( ', ', $str) );
//                                   ^
Sign up to request clarification or add additional context in comments.

1 Comment

explode(', ', ... since it looks like there is also a space in there.
2
$arr = array();

foreach ($myTable AS $t) {
    $str = $t->myStr;
    $arr = array_merge($arr, explode(', ', $str))
} 

$arr = array_unique($arr);
asort($arr);

print_r($arr);

2 Comments

use explode for extract separated data from string
explode(', ', ... since it looks like there is also a space in there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.