Matrices PHP, agregando profundidad de elemento de matriz de forma recursiva a una matriz con la clave de 'profundidad'

StackOverflow https://stackoverflow.com/questions/435180

Pregunta

Según la matriz de ejemplo en la parte inferior, quiero poder agregar la profundidad de cada matriz incrustada dentro de la matriz. por ejemplo:

    array (
      53 => 
      array (
        'title' => 'Home',
        'path' => '',
        'type' => '118',
        'pid' => 52,
        'hasChildren' => 0,
      ),

Tiene una profundidad de uno de acuerdo con la matriz de muestra que se muestra a continuación, por lo que ahora debería verse así:

    array (
      53 => 
      array (
        'title' => 'Home',
        'path' => '',
        'type' => '118',
        'pid' => 52,
        'hasChildren' => 0,
        'depth' => 1,
      ),

y así sucesivamente ...

Todos los intentos de función de matriz recursiva que he hecho son bastante vergonzosos. Sin embargo, he mirado RecursiveArrayIterator que tiene la función getDepth. Estoy confundido sobre cómo agregarlo a la matriz actual ... cualquier ayuda es muy apreciada, gracias.

 
  array (
    'title' => 'Website Navigation',
    'path' => '',
    'type' => '115',
    'pid' => 0,
    'hasChildren' => 1,
    'children' => 
    array (
      53 => 
      array (
        'title' => 'Home',
        'path' => '',
        'type' => '118',
        'pid' => 52,
        'hasChildren' => 0,
      ),
      54 => 
      array (
        'title' => 'Features',
        'path' => 'features',
        'type' => '374',
        'pid' => 52,
        'hasChildren' => 1,
        'children' => 
        array (
          59 => 
          array (
            'title' => 'artistic',
            'path' => 'features/artistic',
            'type' => '374',
            'pid' => 54,
            'hasChildren' => 1,
            'children' => 
            array (
              63 => 
              array (
                'title' => 'galleries',
                'path' => 'features/artistic/galleries',
                'type' => '374',
                'pid' => 59,
                'hasChildren' => 1,
                'children' => 
                array (
                  65 => 
                  array (
                    'title' => 'graphics',
                    'path' => 'features/artistic/galleries/graphics',
                    'type' => '118',
                    'pid' => 63,
                    'hasChildren' => 0,
                  ),
                  67 => 
                  array (
                    'title' => 'mixed medium',
                    'path' => 'features/artistic/galleries/mixed-medium',
                    'type' => '118',
                    'pid' => 63,
                    'hasChildren' => 0,
                  ),
                  64 => 
                  array (
                    'title' => 'overview',
                    'path' => 'features/artistic/galleries',
                    'type' => '118',
                    'pid' => 63,
                    'hasChildren' => 0,
                  ),
                  68 => 
                  array (
                    'title' => 'photography',
                    'path' => 'features/artistic/galleries/photography',
                    'type' => '118',
                    'pid' => 63,
                    'hasChildren' => 0,
                  ),
                  66 => 
                  array (
                    'title' => 'traditional',
                    'path' => 'features/artistic/galleries/traditional',
                    'type' => '118',
                    'pid' => 63,
                    'hasChildren' => 0,
                  ),
                ),
              ),
              62 => 
              array (
                'title' => 'overview',
                'path' => 'features/artistic',
                'type' => '118',
                'pid' => 59,
                'hasChildren' => 0,
              ),
              69 => 
              array (
                'title' => 'tutorials',
                'path' => 'features/artistic/tutorials',
                'type' => '374',
                'pid' => 59,
                'hasChildren' => 1,
                'children' => 
                array (
                  71 => 
                  array (
                    'title' => 'by category',
                    'path' => 'features/artistic/tutorials/by-category/',
                    'type' => '118',
                    'pid' => 69,
                    'hasChildren' => 0,
                  ),
                  72 => 
                  array (
                    'title' => 'by date',
                    'path' => 'features/artistic/tutorials/by-date/',
                    'type' => '118',
                    'pid' => 69,
                    'hasChildren' => 0,
                  ),
                  70 => 
                  array (
                    'title' => 'overview',
                    'path' => 'features/artistic/tutorials',
                    'type' => '118',
                    'pid' => 69,
                    'hasChildren' => 0,
                  ),
                ),
              ),
            ),
          ),
          58 => 
          array (
            'title' => 'overview',
            'path' => 'features',
            'type' => '118',
            'pid' => 54,
            'hasChildren' => 0,
          ),
          61 => 
          array (
            'title' => 'projects / labs',
            'path' => 'features/projects-labs/',
            'type' => '374',
            'pid' => 54,
            'hasChildren' => 0,
          ),
          60 => 
          array (
            'title' => 'web development',
            'path' => 'features/web-development',
            'type' => '374',
            'pid' => 54,
            'hasChildren' => 1,
            'children' => 
            array (
              74 => 
              array (
                'title' => 'articles',
                'path' => 'features/web-development/articles/',
                'type' => '374',
                'pid' => 60,
                'hasChildren' => 0,
              ),
              73 => 
              array (
                'title' => 'overview',
                'path' => 'features/web-development',
                'type' => '118',
                'pid' => 60,
                'hasChildren' => 0,
              ),
              75 => 
              array (
                'title' => 'tutorials',
                'path' => 'features/web-development/tutorials',
                'type' => '374',
                'pid' => 60,
                'hasChildren' => 0,
              ),
            ),
          ),
        ),
      ),
      55 => 
      array (
        'title' => 'Activity',
        'path' => 'activity',
        'type' => '374',
        'pid' => 52,
        'hasChildren' => 0,
      ),
      56 => 
      array (
        'title' => 'Blog',
        'path' => 'blog',
        'type' => '374',
        'pid' => 52,
        'hasChildren' => 0,
      ),
      57 => 
      array (
        'title' => 'About',
        'path' => 'about',
        'type' => '374',
        'pid' => 52,
        'hasChildren' => 1,
        'children' => 
        array (
          76 => 
          array (
            'title' => 'the author',
            'path' => 'about/the-author',
            'type' => '118',
            'pid' => 57,
            'hasChildren' => 0,
          ),
          77 => 
          array (
            'title' => 'the website',
            'path' => 'about/the-website',
            'type' => '118',
            'pid' => 57,
            'hasChildren' => 0,
          ),
        ),
      ),
    ),
  ),
);

print_r($example);

?>
¿Fue útil?

Solución

Supongo que hay otra matriz (en la parte superior no incluida en su código de ejemplo. Algo como esto?

function array_set_depth($array, $depth = -1)
{
  $subdepth = $depth + 1;
  if ($depth < 0) {
    foreach ($array as $key => $subarray) {
      $temp[$key] = array_set_depth(($subarray), $subdepth);
    }
  }
  if ($array['hasChildren'] && isset($array['children'])) {
    foreach ($array['children'] as $key => $subarray) {
      $temp[$key] = array_set_depth($subarray, $subdepth);
    }
    $array['children'] = $temp;
  }
  $array['depth'] = $depth;
  return $array;
}

Ejemplo de uso, configuro su matriz en el valor $ a:

$b = array_set_depth($a);
print_r($b);

Editar:

Para establecer la profundidad antes de los niños para una buena impresión, puede hacer esto:

function array_set_depth($array, $depth = -1)
{
  $subdepth = $depth + 1;
  if ($depth < 0) {
    foreach ($array as $key => $subarray) {
      $temp[$key] = array_set_depth(($subarray), $subdepth);
    }
    return $temp;
  }
  $array['depth'] = $depth;
  if ($array['hasChildren'] && isset($array['children'])) {
    foreach ($array['children'] as $key => $subarray) {
      $temp[$key] = array_set_depth($subarray, $subdepth);
    }
    unset($array['children']);
    $array['children'] = $temp;
  }
  return $array;
}

Otros consejos

¿Una función recursiva como esta debería hacerlo?

function setDepth(&$a, $depth)
{
    $a['depth']=$depth;
    foreach($a as $key=>$value)
    {
        if (is_array($value))
           setDepth($a[$key], $depth+1);
    }

}

Lo que hay que tener en cuenta es que la matriz se pasa por referencia, para que podamos modificarla. Tenga en cuenta que también usamos esta referencia en la llamada recursiva para establecer Profundidad. Aunque utilicé foreach por conveniencia, la variable $ value es una copia, y pasar eso a setDepth solo haría cambios de corta duración dentro del alcance del bucle foreach.

Código Pauls modificado para trabajar con este ejemplo.

function setDepth(&$a, $depth = -1)
{
    if (($depth > -1) && !($depth % 2))
      $a['depth']= $depth / 2;
    foreach($a as $key=>$value)
    {
        if (is_array($value))
           setDepth($a[$key], $depth+1);
    }

}
setDepth($a);
print_r($a);

algo como esto debería hacer el truco:

function setdepth($arr, $depth = 0)
{
    foreach ($arr as $key => $val)
    {
        $arr[$key]['depth'] = $depth;
        if ($arr[$key]['hasChildren'])
        {
            setdepth(&$arr[$key]['children'], $depth+1);
        }
    }
}

Sería más fácil si su matriz comenzara con índice, no con valores, por lo que el uso de ejemplo podría ser así:

$arr[0] = $website;
setdepth(&$arr, 0);

donde el sitio web es la matriz de su ejemplo

Esto puede ser útil:

function extend( $arr, $myArr=array() ) {

    foreach( $arr as $key => $value ) {
        if( is_array( $key ) ) {
            extend( $arr[ $key ] );
        } else {
            $myArr[ $key ] = $arr[ $key ];
        }
    }

    return $myArr;
}

Función llamada " extender " porque no solo copia la matriz en una nueva, también puede extender las matrices existentes.

Para extender una matriz, debe colocarla como el segundo parámetro; de lo contrario, coloque una matriz vacía. La función recorre las propiedades de la matriz y comprueba si es una matriz o no, y si se vuelve a invocar, de lo contrario, copia los valores en otra matriz y la devuelve.

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