将点分隔的键路径字符串和值声明转换为多维关联数组

发布于 2024-12-13 11:10:02 字数 250 浏览 0 评论 0原文

我正在尝试创建一个数组,同时解析用点分隔的字符串

$string = "foo.bar.baz";
$value = 5

,以

$arr['foo']['bar']['baz'] = 5;

解析键,

$keys = explode(".",$string);

我怎样才能做到这一点?

I'm trying to create an array while parsing a string separated with dots

$string = "foo.bar.baz";
$value = 5

to

$arr['foo']['bar']['baz'] = 5;

I parsed the keys with

$keys = explode(".",$string);

How could I do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

走野 2024-12-20 11:10:02

您可以执行以下操作:

$keys = explode(".",$string);
$last = array_pop($keys);

$array = array();
$current = &$array;

foreach($keys as $key) {
    $current[$key] = array();
    $current = &$current[$key];
}

$current[$last] = $value;

DEMO

如果传递字符串,您可以轻松制作一个函数以及作为参数的值并返回数组。

You can do:

$keys = explode(".",$string);
$last = array_pop($keys);

$array = array();
$current = &$array;

foreach($keys as $key) {
    $current[$key] = array();
    $current = &$current[$key];
}

$current[$last] = $value;

DEMO

You can easily make a function out if this, passing the string and the value as parameter and returning the array.

满身野味 2024-12-20 11:10:02

您可以尝试以下解决方案:

function arrayByString($path, $value) {
  $keys   = array_reverse(explode(".",$path));

  foreach ( $keys as $key ) {
    $value = array($key => $value);
  }

  return $value;
}

$result = arrayByString("foo.bar.baz", 5);

/*
array(1) {
  ["foo"]=>
  array(1) {
    ["bar"]=>
    array(1) {
      ["baz"]=>
      int(5)
    }
  }
}
*/

You can try following solution:

function arrayByString($path, $value) {
  $keys   = array_reverse(explode(".",$path));

  foreach ( $keys as $key ) {
    $value = array($key => $value);
  }

  return $value;
}

$result = arrayByString("foo.bar.baz", 5);

/*
array(1) {
  ["foo"]=>
  array(1) {
    ["bar"]=>
    array(1) {
      ["baz"]=>
      int(5)
    }
  }
}
*/
爱的那么颓废 2024-12-20 11:10:02

这在某种程度上与您可以在此处找到答案的问题相关:

PHP 每个循环在数组中更深一层

您只需稍微更改一下代码:

$a = explode('.', "foo.bar.baz");
$b = array();
$c =& $b;

foreach ($a as $k) {
    $c[$k] = array();
    $c     =& $c[$k];
}

$c = 5;

print_r($b);

This is somehow related to the question you can find an answer to, here:

PHP One level deeper in array each loop made

You would just have to change the code a little bit:

$a = explode('.', "foo.bar.baz");
$b = array();
$c =& $b;

foreach ($a as $k) {
    $c[$k] = array();
    $c     =& $c[$k];
}

$c = 5;

print_r($b);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文