I don't like to promote variable variables, but it does satisfy your requirement of individualized variables in a very concise way.
strstr()
with a 3rd parameter of true
will isolate the table alias which is then used as the array variable's name.
Code (Demo)
$sample = array('a.col1','a.col2','b.col1','c.col1','c.col2','d.col5');
foreach ($sample as $column) {
${strstr($column, '.', true)}[] = $column;
}
var_export($a);
var_export($b);
var_export($c);
var_export($d);
Output:
array (
0 => 'a.col1',
1 => 'a.col2',
)array (
0 => 'b.col1',
)array (
0 => 'c.col1',
1 => 'c.col2',
)array (
0 => 'd.col5',
)
After question update...
You can split your strings into two halves using the dot as the delimiter. I can't imagine more than one dot in the strings, but I use the 3rd parameter of explode()
to improve clarity and allow the function to finish quickly.
Rather than calling list()
to declare variables for the exploded values, I am using square brace syntax to spare iterated function calls.
Code: (Demo)
foreach ($sample as $column) {
[$alias, $column] = explode('.', $column, 2);
$$alias[] = $column;
}
Output:
array (
0 => 'col1',
1 => 'col2',
)array (
0 => 'col1',
)array (
0 => 'col1',
1 => 'col2',
)array (
0 => 'col5',
)