将点阵列转换为关联阵列



在laravel中,有没有任何函数可以用I将用点划分的string转换为associative array

例如:

user.profile.settings转化为['user' => ['profile' => 'settings']]

我找到了methodarray_dot,但它的工作方式正好相反。

array_dot的反向并不是您所要求的,因为它仍然需要一个关联数组,并返回一个关联阵列,而您只有一个字符串。

我想你可以很容易地做到这一点。

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默认情况下只为您提供array_dot((助手,您可以使用它将多维数组展开为点表示数组。

可能的解决方案

最简单的方法是使用这个小包,它将array_undot((helper添加到你的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;
}
Laravel有一个数组undot方法。
use IlluminateSupportArr;

$array = [
'user.name' => 'Kevin Malone',
'user.occupation' => 'Accountant',
];

$array = Arr::undot($array);

// ['user' => ['name' => 'Kevin Malone', 'occupation' => 'Accountant']]

参考:https://laravel.com/docs/8.x/helpers#method-阵列脱离

Laravel没有提供这样的函数。

最新更新