Remove first levels of identifier in array

Fredrik picture Fredrik · Feb 28, 2012 · Viewed 26.2k times · Source

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

Answer

prodigitalson picture prodigitalson · Feb 28, 2012

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