PHP Arrays, acrescentando profundidade de item da matriz de forma recursiva para uma matriz com a chave da 'profundidade'

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

Pergunta

Por exemplo série na parte inferior, eu quero ser capaz de acrescentar a profundidade de cada dentro variedade incorporado da matriz. por exemplo:

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

Tem uma profundidade de um acordo com a matriz de exemplo mostrado abaixo, por isso agora deve ter esta aparência:

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

e assim por diante ...

Todas as tentativas função array recursivo i fizeram são bastante embaraçoso. No entanto Eu olhei RecursiveArrayIterator que tem a função getDepth. Estou confuso sobre como anexá-lo para a matriz atual ... qualquer ajuda é muito apreciada, obrigado.

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

?>
Foi útil?

Solução

Eu assumo há um outro array (no topo não incluídos em seu código exemplo. Algo como isso?

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

Exemplo de uso, eu definir a sua matriz para o valor $ a:

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

Editar:

Para definir a profundidade diante dos filhos para boa impressão que você pode fazer isso:

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

Outras dicas

A função recursiva como isso deve fazê-lo?

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

}

A primeira coisa a notar é que a matriz é passada por referência, para que possamos modificá-lo. Note que nós também usamos esta referência na chamada recursiva para setDepth. Embora eu usei foreach por conveniência, a variável $ value é uma cópia, e passando isso para setDepth só iria fazer mudanças curta duração no âmbito do loop foreach.

Pauls Modificados código para trabalhar com este exemplo.

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

sth como este deve fazer o truque:

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

i seria mais fácil se a matriz começou com índice não com os valores, de modo exemplo de uso poderia ser assim:

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

onde o sítio é a matriz do seu exemplo

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

Função chamado de "estender", porque não é só conjunto de cópias em um novo, ele pode também se estende matrizes existentes.

Para estender uma matriz que você deve colocá-lo como o segundo parâmetro, caso contrário, colocar um array vazio. A função lopps através propriedades da matriz e controlos é uma matriz ou não e se é função envoked novamente caso contrário valores copia em outra matriz e devolve-lo.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top