所以我有多个我要填充的空数组,让我们说
$a_tab = [];
$b_tab = [];
$c_tab = [];
我有一个包含一些数据的数组,让我们说
$data = ['a' => 'foo', 'b' => 'bar', 'c' => 'foobar'];
我希望能够做到这样的事情:
foreach($data as $key => $value) {
$tab_name = $key . '_tab'; // so we have a variable that have the same name as one of the array we declared before
$$tab_name[$value] = $value; // this should add 'foo' into $a_tab, 'bar' in $b_tab and 'foobar' in $c_tab
}
但是没有任何值被添加到任何数组......
有人可以解释一下我做错了什么吗?
PS:如果你不想要伪代码,这是我遇到问题时的代码:
// $tab is a parameter of the current function
$done_courses = []; // the array where we are going to put every courses that already have been added in one bifurcation tab
$regex_wz = '/\_werkzoekende/';
$regex_bd = '/\_bediende/';
$regex_op = '/\_outplacement/';
$bifurcation_keys = ['wz_tab' => $regex_wz, 'bd_tab' => $regex_bd, 'op_tab' => $regex_op];
// create the 3 arrays
$wz_tab = [];
$bd_tab = [];
$op_tab = [];
foreach($tab as $key => $value) {
foreach($bifurcation_keys as $tab_name => $regex) {
if(preg_match($regex, $key)) {
$n_k = preg_replace($regex, '', $key);
$$tab_name[$n_k] = $value;
if(!isset($done_courses[$n_k])) {
$done_courses[$n_k] = $n_k;
}
}
}
}
答案 0 :(得分:1)
你试过..
foreach($data as $key => $value) {
${$key.'_tab'}[$value] = $value;
}