将点数组转换为关联数组
Transform dot array to associative array
在laravel中,是否有任何函数可以将用点划分的string
转换为associative array
?
例如:
user.profile.settings
变成 ['user' => ['profile' => 'settings']]
?
我找到了 method
array_dot
,但它的工作方式相反。
Laravel 不提供这样的功能。
不,Laravel 默认只给你 array_dot() 帮助程序,你可以用它来将多维数组扁平化为点符号数组。
可能的解决方案
最简单的方法是使用 this 小包将 array_undot() 助手添加到您的 Laravel,然后就像包文档所说的那样,您可以这样做:
$dotNotationArray = ['products.desk.price' => 100,
'products.desk.name' => 'Oak Desk',
'products.lamp.price' => 15,
'products.lamp.name' => 'Red Lamp'];
$expanded = array_undot($dotNotationArray)
/* print_r of $expanded:
[
'products' => [
'desk' => [
'price' => 100,
'name' => 'Oak Desk'
],
'lamp' => [
'price' => 15,
'name' => 'Red Lamp'
]
]
]
*/
另一种可能的解决方案是使用以下代码创建辅助函数:
function array_undot($dottedArray) {
$array = array();
foreach ($dottedArray as $key => $value) {
array_set($array, $key, $value);
}
return $array;
}
array_dot
的反面并不是您所要求的,因为它仍然需要一个关联数组和 returns 一个关联数组,而您只有一个字符串。
虽然我想你可以很容易地做到这一点。
function yourThing($string)
{
$pieces = explode('.', $string);
$value = array_pop($pieces);
array_set($array, implode('.', $pieces), $value);
return $array;
}
这假设您传递的字符串至少有一个点(至少一个键 [在最后一个点之前] 和一个值 [在最后一个点之后])。您可以将其扩展为与字符串数组一起使用,并轻松添加适当的检查。
>>> yourThing('user.profile.settings')
=> [
"user" => [
"profile" => "settings",
],
]
在laravel中,是否有任何函数可以将用点划分的string
转换为associative array
?
例如:
user.profile.settings
变成 ['user' => ['profile' => 'settings']]
?
我找到了 method
array_dot
,但它的工作方式相反。
Laravel 不提供这样的功能。
不,Laravel 默认只给你 array_dot() 帮助程序,你可以用它来将多维数组扁平化为点符号数组。
可能的解决方案
最简单的方法是使用 this 小包将 array_undot() 助手添加到您的 Laravel,然后就像包文档所说的那样,您可以这样做:
$dotNotationArray = ['products.desk.price' => 100,
'products.desk.name' => 'Oak Desk',
'products.lamp.price' => 15,
'products.lamp.name' => 'Red Lamp'];
$expanded = array_undot($dotNotationArray)
/* print_r of $expanded:
[
'products' => [
'desk' => [
'price' => 100,
'name' => 'Oak Desk'
],
'lamp' => [
'price' => 15,
'name' => 'Red Lamp'
]
]
]
*/
另一种可能的解决方案是使用以下代码创建辅助函数:
function array_undot($dottedArray) {
$array = array();
foreach ($dottedArray as $key => $value) {
array_set($array, $key, $value);
}
return $array;
}
array_dot
的反面并不是您所要求的,因为它仍然需要一个关联数组和 returns 一个关联数组,而您只有一个字符串。
虽然我想你可以很容易地做到这一点。
function yourThing($string)
{
$pieces = explode('.', $string);
$value = array_pop($pieces);
array_set($array, implode('.', $pieces), $value);
return $array;
}
这假设您传递的字符串至少有一个点(至少一个键 [在最后一个点之前] 和一个值 [在最后一个点之后])。您可以将其扩展为与字符串数组一起使用,并轻松添加适当的检查。
>>> yourThing('user.profile.settings')
=> [
"user" => [
"profile" => "settings",
],
]