Pregunta

how can I add an extra dimesion before each element in N-dimensional array (recursively)? Let's say I have

Array
(
    [room] => Array
        (
            [bed] = Array
                (
                    [material] => wood
                )
        )
)

And I want to add an extra "[0]" dimension before room, bed and material. (Adding dimension only if the last element is an array). I also want to distinguish, if there already is the extra [0] dimension, so it will not appear twice .. + I don't want to add [0] if the array key is named "@attribute".

I'm trying to figure it out, but I'm really lost. This is what I've got so far..

function normalize_array (&$array) {
    if (is_array($array)) {
        if (!isset($array[0])) {
            $array = array ( "0" => $array);
        }
        foreach ($array[0] as $next) {
            normalize_array ($next);
        }
    }
}

but it does not work recursively. Any help will be appreciated. Thanks!

¿Fue útil?

Solución

From the documentation of foreach:

In order to be able to directly modify array elements within the loop
precede $value with &. In that case the value will be assigned by reference.

So if you modify your function like this, it works:

function normalize_array (&$array) {
    if (is_array($array)) {
        if (!isset($array[0])) {
            $array = array ( "0" => $array);
        }
        foreach ($array[0] as &$next) { // <-- add & here
            normalize_array ($next);
        }
    }
}

Otros consejos

Possible solution (tested just a little, but seems to work):

function normalize_array($array, $keys){
  $new = array();
  foreach($array as $key => $value){
    if (in_array($key, $keys) && is_array($value)){
      $new["0"] =  array($key => normalize_array($value, $keys));
    } else {
      $new[$key] = $value ;
    }
  }
  return $new ;
}

$data = array(
 "room" => array(
        "bed" => array(
            "material" => "wood"
        )
    )
);


$keys = array("room", "bed", "material");

$new = normalize_array($data, $keys);
var_dump($new);

Final solution:

function normalize_array_rec (&$array) {
        if (is_array($array)) {
                if (!isset($array[0])) {
                        $array = array ( "0" => $array);
                }
                $i = 0;
                while (isset($array[$i])) {
                        foreach ($array[$i] as &$next) {
                                normalize_array_rec ($next);                           
                        }
                        $i++;                          
                }              
        }
}

Forgot to call function in each instance of array, not only in [0] index.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top