按二级键对包含单元素关联行的数组进行分组,以形成索引元素的关联数组

发布于 2024-12-27 19:40:00 字数 583 浏览 5 评论 0原文

我有一个数组,其中包含数据如下:

[
    0 => ['www.google.com' => 'www.google.com/a'],
    1 => ['www.google.com' => 'www.google.com/a'],
    2 => ['www.test.com' => 'www.test.com'],
    5 => ['www.test.com' => 'www.test.com/c'],
]

我需要对特定 url 的所有链接进行分组,如下所示:

Array (
 [www.google.com] => Array (
      [0] => www.google.com/a
      [1] => www.google.com/a
      )
 [www.test.com] => Array (
      [0] => www.test.com
      [1] => www.test.com/c
      )
  )

I have an array, which contains data as follows:

[
    0 => ['www.google.com' => 'www.google.com/a'],
    1 => ['www.google.com' => 'www.google.com/a'],
    2 => ['www.test.com' => 'www.test.com'],
    5 => ['www.test.com' => 'www.test.com/c'],
]

I need to group all links for particular url like this:

Array (
 [www.google.com] => Array (
      [0] => www.google.com/a
      [1] => www.google.com/a
      )
 [www.test.com] => Array (
      [0] => www.test.com
      [1] => www.test.com/c
      )
  )

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

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

发布评论

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

评论(2

枕花眠 2025-01-03 19:40:00

如果我们调用第一个数组$domains

$groups = array();

for ($i = 0; $i <= count($domains); $i++)
{
    foreach ($domains[$i] as $domain => $url)
    {
         $groups[$domain][] = $url;
    }
}

print_r($groups);

这可能有用...

If we call the first array $domains.

$groups = array();

for ($i = 0; $i <= count($domains); $i++)
{
    foreach ($domains[$i] as $domain => $url)
    {
         $groups[$domain][] = $url;
    }
}

print_r($groups);

That might work...

祁梦 2025-01-03 19:40:00

只需使用两个循环来访问嵌套的关联元素,并按二级键对数据进行分组,同时将值推入子数组中。 演示

$result = [];
foreach ($array as $row) {
    foreach ($row as $k => $v) {
        $result[$k][] = $v;
    }
}
var_export($result);

输出:

array (
  'www.google.com' => 
  array (
    0 => 'www.google.com/a',
    1 => 'www.google.com/a',
  ),
  'www.test.com' => 
  array (
    0 => 'www.test.com',
    1 => 'www.test.com/c',
  ),
)

Simply use two loops to access the nested associative elements and group the data by second level keys while pushing the values into subarrays. Demo

$result = [];
foreach ($array as $row) {
    foreach ($row as $k => $v) {
        $result[$k][] = $v;
    }
}
var_export($result);

Output:

array (
  'www.google.com' => 
  array (
    0 => 'www.google.com/a',
    1 => 'www.google.com/a',
  ),
  'www.test.com' => 
  array (
    0 => 'www.test.com',
    1 => 'www.test.com/c',
  ),
)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文