我有此功能
public function saveVariantValue($id, $data, $langs, $field, $client)
{
$transformation = [];
$parts1 = explode(';', $data[$field][1]);
$parts2 = explode(';', $data[$field][2]);
$tmp_arr = array_map(null, $parts1, $parts2);
$transformation[] = array_map(
function($v) { return array_combine(["1","2"], $v); },
$tmp_arr
);
//here i use the transformation array//
}
该函数从中转换输入数组
[
{
"1": "tag_es1;tag_es2;tag_es3",
"2": "tag_en1;tag_en2;tag_en3"
}
]
对此
[
{
{
"1" : "tag_es1",
"2" : "tag_en1"
},
{
"1" : "tag_es2",
"2" : "tag_en2"
},
{
"1" : "tag_es3",
"2" : "tag_en3"
}
}
]
每个1
和2
代表数据库中的一种语言ID,如果您检查代码,则仅当我同时发送两种语言时才有效,但是在某些情况下,基于用户的许可,用户将能够发送
[
{
"1": "tag_es1;tag_es2;tag_es3"
}
]
我想动态地设置代码模式,因此无需声明parts1
和parts2
,而是可以创建一个值字符串,然后像这样评估字符串
$str = '';
$eval = '';
foreach($langs as $l) {
//i create the string "variables", the values of the "parts" must be an array, that's why the explode
$str .= 'parts'.$l->id.'='.serialize(explode(";", $variant[$l->id])).';&';
//i need to pass the "parts" to array_map so i create a string to pass it as the function parameters;
$eval .= '$parts'.$l->id.', ';
}
$str = rtrim($str, '&');
$eval = rtrim($eval, ', ');
parse_str($str);
//if i var_dump $parts1 or $parts2 i get the correct values
$tmp_arr = array_map(null, eval($eval));//here i fail
到目前为止,当我调用array_map时,它无法抛出syntax error, unexpected end of file
所以问题来了,我该如何使此代码起作用?可以这样做吗?有更好的方法吗?
答案 0 :(得分:2)
阅读有关variadic arguments的信息,并使用它:
$a = '1,2,3';
$b = '4,5,6';
$c = '7,8,9';
$r = [1 => $a, 2 => $b, 3 => $c];
$parts = array_map(function($v) { return explode(',', $v); }, $r);
print_r(array_map(null, ...$parts));