Reputation: 12512
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'...);
Upvotes: 1
Views: 63
Reputation: 11689
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.
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) );
// ^
Upvotes: 3
Reputation: 2889
$arr = array();
foreach ($myTable AS $t) {
$str = $t->myStr;
$arr = array_merge($arr, explode(', ', $str))
}
$arr = array_unique($arr);
asort($arr);
print_r($arr);
Upvotes: 2