Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...