将点数组转换为关联数组

问题描述 投票:0回答:4

在 laravel 中,是否有任何函数可以将用点划分的

string
转换为
associative array

例如:

user.profile.settings
进入
['user' => ['profile' => 'settings']]
?

我找到了

method
array_dot
,但它的工作方式相反。

arrays string laravel laravel-5.5
4个回答
3
投票

不,默认情况下,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;
}

2
投票

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",
     ],
   ]

0
投票

Laravel 不提供这样的功能。


0
投票

Laravel 有一个数组取消点方法。

use Illuminate\Support\Arr;
 
$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-array-undot

© www.soinside.com 2019 - 2024. All rights reserved.