如何在 ucwords 中使用 extract php 函数
How use extract php function with ucwords
我想知道如何使用 php 提取函数从数组中提取键以将变量 snake_case 更改为 camel_case。
示例:
array('id' => 1, 'user_name' => 'Paul');
至
$id = 1;
$userName = 'Paul';
我正在使用 laravel 框架。
谢谢;)
你不能 extract
。
Quoting the PHP Manual(强调我的):
array: An associative array. This function treats keys as variable names and values as variable values. For each key/value pair it will create a variable in the current symbol table, subject to flags and prefix parameters.
没有改变按键大小写的标志。它将使用数组中出现的数组键作为变量名。如果你想要驼峰大小写,你需要改变数组键。 extract
.
别无他法
您可以使用这段代码在用户空间中执行此操作:
$data = array('id' => 1, 'user_name' => 'Paul');
foreach ($data as $k => $v) {
${lcfirst(str_replace('_', '', ucwords($k, '_')))} = $v;
}
echo $userName;
而且显然,Laravel has a helper function 在幕后做了大致相同的事情。
但说真的……不要。这样做是非常没有意义的。把key改成驼峰式完全是浪费CPU。只需使用 $user_name
或 $data['user_name']
.
foreach($array as $key => $value) {
$name = camel_case($key);
$$name = $value;
}
我想知道如何使用 php 提取函数从数组中提取键以将变量 snake_case 更改为 camel_case。 示例:
array('id' => 1, 'user_name' => 'Paul');
至
$id = 1;
$userName = 'Paul';
我正在使用 laravel 框架。
谢谢;)
你不能 extract
。
Quoting the PHP Manual(强调我的):
array: An associative array. This function treats keys as variable names and values as variable values. For each key/value pair it will create a variable in the current symbol table, subject to flags and prefix parameters.
没有改变按键大小写的标志。它将使用数组中出现的数组键作为变量名。如果你想要驼峰大小写,你需要改变数组键。 extract
.
您可以使用这段代码在用户空间中执行此操作:
$data = array('id' => 1, 'user_name' => 'Paul');
foreach ($data as $k => $v) {
${lcfirst(str_replace('_', '', ucwords($k, '_')))} = $v;
}
echo $userName;
而且显然,Laravel has a helper function 在幕后做了大致相同的事情。
但说真的……不要。这样做是非常没有意义的。把key改成驼峰式完全是浪费CPU。只需使用 $user_name
或 $data['user_name']
.
foreach($array as $key => $value) {
$name = camel_case($key);
$$name = $value;
}