删除数组中的第一级标识符 [英] Remove first levels of identifier in array

查看:21
本文介绍了删除数组中的第一级标识符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这之前已经出现过,但找不到任何答案.如果已经回答了,请通过链接为我指明正确的方向.

I think this has been up before, but could'nt find any answer to it. If it's already answered please point me in the right direction with a link.

我有一个数组,我不想删除标识符的第一级.我认为有这个功能吗?

I have an array that I wan't to remove the first levels of identifier. I think there is a function for this?

示例:

[0] => Array
        (
            [8] => Röd
        )

[1] => Array
        (
            [8] => Blå
        )

[2] => Array
        (
            [6] => Bobo
        )

[3] => Array
        (
            [8] => Grön
        )

[4] => Array
        (
            [7] => Sten
        )

[5] => Array
        (
            [8] => Vit
        )

[6] => Array
        (
            [7] => Guld
        )

[7] => Array
        (
            [6] => Lyxig
        )

我不想要的

[8] => Röd
[8] => Blå
[6] => Bobo
[8] => Grön
[7] => Sten
[8] => Vit
[7] => Guld
[6] => Lyxig

推荐答案

这里的问题是保留所需标识符的键.您有一些具有相同键的名称字符串(如 Blå 和 Röd).您要么需要将这些存储在数组中,要么愿意丢失密钥.

The problem here is preserving the keys for the identifier you want. You have some names strings that have the same key (like Blå and Röd). You either need to store these in an array or be willing to lose the key.

以 php5.3 为例:

Example with php5.3:

$processed = array_map(function($a) {  return array_pop($a); }, $arr);

这会给你:

[0] => Röd
[1] => Blå
[2] => Bobo
[3] => Grön
[4] => Sten
[5] => Vit
[6] => Guld
[7] => Lyxig

很明显,需要保留内部数组上的键,因为它们是某种 id.话虽如此,您必须更改您要使用的最终结构,因为您可以在单个数组中拥有 2 个相同的键.最简单的结构就变成了:

It has become clear the keys on the inner array need to be preserved because they are some kind of id. With that said you must change the end structure you're going for because you can have 2 of the same key in a single array. The simplest structure then becomes:

[8] => Array
        (
            [0] => Röd,
            [1] => Blå,
            [2] => Vit,
            [3] => Grön
        )

[6] => Array
        (
            [0] => Bobo,
            [1] => Lyxig
        )

[7] => Array
        (
            [0] => Sten,
            [1] => Guld
        )

为了得到这个结构,一个简单的循环就可以工作:

To get this structure a simple loop will work:

$processed = array();
foreach($arr as $subarr) {
   foreach($subarr as $id => $value) {
      if(!isset($processed[$id])) {
         $processed[$id] = array();
      }

      $processed[$id][] = $value;
   }
}

这篇关于删除数组中的第一级标识符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆