Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

php - Remove first levels of identifier in array

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?

Example of how it is:

[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
        )

What I wan't

[8] => R?d
[8] => Bl?
[6] => Bobo
[8] => Gr?n
[7] => Sten
[8] => Vit
[7] => Guld
[6] => Lyxig
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Example with php5.3:

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

This will give you:

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

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;
   }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...