PHP: Ordenar una matriz -- php campo con arrays campo con sorting campo con nested-sets camp Relacionados El problema

PHP: Sort an array


4
vote

problema

Español

Tengo una matriz con datos de una tabla MySQL en un modelo establecido anidado, me gustaría ser ordenado, no solo alfabético, sino también con los nodos infantiles directamente después del nodo principal. Ejemplo: la matriz para ser ordenada (antes de la clasificación):

  Array (     [0] => Array         (             [id] => 1             [name] => Kompetenser             [parent] => 0             [depth] => 0         )      [1] => Array         (             [id] => 2             [name] => Administration             [parent] => 1             [depth] => 1         )      [2] => Array         (             [id] => 11             [name] => Organisation             [parent] => 2             [depth] => 2         )      [3] => Array         (             [id] => 4             [name] => Arbetsledning             [parent] => 2             [depth] => 2         )      [4] => Array         (             [id] => 17             [name] => Planering             [parent] => 2             [depth] => 2         )      [5] => Array         (             [id] => 9             [name] => Hantverke             [parent] => 1             [depth] => 1         )      [6] => Array         (             [id] => 10             [name] => Snickeri             [parent] => 9             [depth] => 2         )      [7] => Array         (             [id] => 12             [name] => Språk             [parent] => 1             [depth] => 1         )      [8] => Array         (             [id] => 13             [name] => Tolk             [parent] => 12             [depth] => 2         )      [9] => Array         (             [id] => 15             [name] => Arabiska             [parent] => 13             [depth] => 3         )      [10] => Array         (             [id] => 14             [name] => Persiska             [parent] => 13             [depth] => 3         )      [11] => Array         (             [id] => 16             [name] => Polska             [parent] => 13             [depth] => 3         )      [12] => Array         (             [id] => 18             [name] => Apotekare             [parent] => 1             [depth] => 1         )      [13] => Array         (             [id] => 19             [name] => Dotkorand             [parent] => 1             [depth] => 1         )      [14] => Array         (             [id] => 21             [name] => Atomfysik             [parent] => 19             [depth] => 2         )      [15] => Array         (             [id] => 20             [name] => Fysik             [parent] => 19             [depth] => 2         )      [16] => Array         (             [id] => 22             [name] => Ekonom             [parent] => 1             [depth] => 1         )      [17] => Array         (             [id] => 23             [name] => Industriell ekonomi             [parent] => 22             [depth] => 2         )      [18] => Array         (             [id] => 24             [name] => Filosofi             [parent] => 1             [depth] => 1         )  )   

Quiero la matriz de esta manera (después de la clasificación):

  Array (     [0] => Array         (             [id] => 1             [name] => Kompetenser             [parent] => 0             [depth] => 0         )      [1] => Array         (             [id] => 2             [name] => Administration             [parent] => 1             [depth] => 1         )      [3] => Array         (             [id] => 4             [name] => Arbetsledning             [parent] => 2             [depth] => 2         )      [2] => Array         (             [id] => 11             [name] => Organisation             [parent] => 2             [depth] => 2         )      [4] => Array         (             [id] => 17             [name] => Planering             [parent] => 2             [depth] => 2         )      [12] => Array         (             [id] => 18             [name] => Apotekare             [parent] => 1             [depth] => 1         )      [13] => Array         (             [id] => 19             [name] => Dotkorand             [parent] => 1             [depth] => 1         )      [14] => Array         (             [id] => 21             [name] => Atomfysik             [parent] => 19             [depth] => 2         )      [15] => Array         (             [id] => 20             [name] => Fysik             [parent] => 19             [depth] => 2         )      [16] => Array         (             [id] => 22             [name] => Ekonom             [parent] => 1             [depth] => 1         )      [17] => Array         (             [id] => 23             [name] => Industriell ekonomi             [parent] => 22             [depth] => 2         )      [18] => Array         (             [id] => 24             [name] => Filosofi             [parent] => 1             [depth] => 1         )      [5] => Array         (             [id] => 9             [name] => Hantverke             [parent] => 1             [depth] => 1         )      [6] => Array         (             [id] => 10             [name] => Snickeri             [parent] => 9             [depth] => 2         )      [7] => Array         (             [id] => 12             [name] => Språk             [parent] => 1             [depth] => 1         )      [8] => Array         (             [id] => 13             [name] => Tolk             [parent] => 12             [depth] => 2         )      [9] => Array         (             [id] => 15             [name] => Arabiska             [parent] => 13             [depth] => 3         )       [10] => Array         (             [id] => 14             [name] => Persiska             [parent] => 13             [depth] => 3         )      [11] => Array         (             [id] => 16             [name] => Polska             [parent] => 13             [depth] => 3         )  )   

Como puede ver, quiero todas las publicaciones con padre 2 directamente después del poste con ID 2, y así sucesivamente.

Cualquier ayuda sería muy apreciada. Gracias de antemano.

Original en ingles

I've got an array with data from a MySQL table in nested set model I'd like to get sorted, not only alphabetical but also with the child nodes directly after the parent node. Example - array to be sorted (before the sorting):

Array (     [0] => Array         (             [id] => 1             [name] => Kompetenser             [parent] => 0             [depth] => 0         )      [1] => Array         (             [id] => 2             [name] => Administration             [parent] => 1             [depth] => 1         )      [2] => Array         (             [id] => 11             [name] => Organisation             [parent] => 2             [depth] => 2         )      [3] => Array         (             [id] => 4             [name] => Arbetsledning             [parent] => 2             [depth] => 2         )      [4] => Array         (             [id] => 17             [name] => Planering             [parent] => 2             [depth] => 2         )      [5] => Array         (             [id] => 9             [name] => Hantverke             [parent] => 1             [depth] => 1         )      [6] => Array         (             [id] => 10             [name] => Snickeri             [parent] => 9             [depth] => 2         )      [7] => Array         (             [id] => 12             [name] => Språk             [parent] => 1             [depth] => 1         )      [8] => Array         (             [id] => 13             [name] => Tolk             [parent] => 12             [depth] => 2         )      [9] => Array         (             [id] => 15             [name] => Arabiska             [parent] => 13             [depth] => 3         )      [10] => Array         (             [id] => 14             [name] => Persiska             [parent] => 13             [depth] => 3         )      [11] => Array         (             [id] => 16             [name] => Polska             [parent] => 13             [depth] => 3         )      [12] => Array         (             [id] => 18             [name] => Apotekare             [parent] => 1             [depth] => 1         )      [13] => Array         (             [id] => 19             [name] => Dotkorand             [parent] => 1             [depth] => 1         )      [14] => Array         (             [id] => 21             [name] => Atomfysik             [parent] => 19             [depth] => 2         )      [15] => Array         (             [id] => 20             [name] => Fysik             [parent] => 19             [depth] => 2         )      [16] => Array         (             [id] => 22             [name] => Ekonom             [parent] => 1             [depth] => 1         )      [17] => Array         (             [id] => 23             [name] => Industriell ekonomi             [parent] => 22             [depth] => 2         )      [18] => Array         (             [id] => 24             [name] => Filosofi             [parent] => 1             [depth] => 1         )  ) 

I want the array this way (after the sorting):

Array (     [0] => Array         (             [id] => 1             [name] => Kompetenser             [parent] => 0             [depth] => 0         )      [1] => Array         (             [id] => 2             [name] => Administration             [parent] => 1             [depth] => 1         )      [3] => Array         (             [id] => 4             [name] => Arbetsledning             [parent] => 2             [depth] => 2         )      [2] => Array         (             [id] => 11             [name] => Organisation             [parent] => 2             [depth] => 2         )      [4] => Array         (             [id] => 17             [name] => Planering             [parent] => 2             [depth] => 2         )      [12] => Array         (             [id] => 18             [name] => Apotekare             [parent] => 1             [depth] => 1         )      [13] => Array         (             [id] => 19             [name] => Dotkorand             [parent] => 1             [depth] => 1         )      [14] => Array         (             [id] => 21             [name] => Atomfysik             [parent] => 19             [depth] => 2         )      [15] => Array         (             [id] => 20             [name] => Fysik             [parent] => 19             [depth] => 2         )      [16] => Array         (             [id] => 22             [name] => Ekonom             [parent] => 1             [depth] => 1         )      [17] => Array         (             [id] => 23             [name] => Industriell ekonomi             [parent] => 22             [depth] => 2         )      [18] => Array         (             [id] => 24             [name] => Filosofi             [parent] => 1             [depth] => 1         )      [5] => Array         (             [id] => 9             [name] => Hantverke             [parent] => 1             [depth] => 1         )      [6] => Array         (             [id] => 10             [name] => Snickeri             [parent] => 9             [depth] => 2         )      [7] => Array         (             [id] => 12             [name] => Språk             [parent] => 1             [depth] => 1         )      [8] => Array         (             [id] => 13             [name] => Tolk             [parent] => 12             [depth] => 2         )      [9] => Array         (             [id] => 15             [name] => Arabiska             [parent] => 13             [depth] => 3         )       [10] => Array         (             [id] => 14             [name] => Persiska             [parent] => 13             [depth] => 3         )      [11] => Array         (             [id] => 16             [name] => Polska             [parent] => 13             [depth] => 3         )  ) 

As you might see, I want all posts with parent 2 directly after the post with id 2, and so on.

Any help would be highly appreciated. Thank you in advance.

</div
           
   
   

Lista de respuestas

4
 
vote

¡No hagas esto en PHP!

El servidor MySQL está diseñado específicamente para consultar y ordenar los datos, lea la lectura en el MYSQL " Orden por "Sintaxis. Hacer esto en el servidor MySQL ahorrará tiempo de ejecución, carga de CPU y consumo de memoria.

 

Don't do this in PHP!

The MySQL server is specificly designed to query AND sort data, read up on the MySQL "ORDER BY" syntax. Doing this on the MySQL server will save run-time, CPU Load and Memory Consumption.

</div
 
 
 
 
2
 
vote

Utilice la función 99887776662 para definir su propia función de comparación.

Pero usar las capacidades de clasificación de MySQL sería más apropiado, si es posible en su caso.

 

Use php's uasort() function to define your own comparison function.

But using MySQL's sorting capabilities would be more appropriate, if it's possible in your case.

</div
 
 
 
 
0
 
vote

Quieres ordenarlo como está en el DB, multicularizado. No creo que Uasort pueda ayudar con este problema porque quiere adjuntar a los niños al padre.

  foreach ($arr as &$val) {     $arr2[$val['id']] = &$val; }  ksort($arr2);  foreach ($arr2 as $id => &$val) {     $parent = $val['parent'];     if ($parent == 0) {         continue;     }     $arr2[$parent]['children'][$id] = &$val; }  function flattenArrayByChildren($arr) {     foreach ($arr as $id => $val) {         if (isset($val['children'])) {             $temp = flattenArrayByChildren($val['children']);             unset($val['children']);             $out[$id] = $val;             $out = $out + $temp;         } else {             $out[$id] = $val;         }     }     return $out; }  $arr2 = array(1 => $arr2[1]);  $out = flattenArrayByChildren($arr2);  var_dump($out);   

Si desea obtener toda la clave, puede agregarlo a los $ Val en el primer foreach, y recuperarlo en la función recursiva FlattenarrayByChildren y usarlo como clave.

 

You want to sort it like it is in the DB, multilayered. I don't think uasort can help with this problem because you want to attach the children to the parent.

foreach ($arr as &$val) {     $arr2[$val['id']] = &$val; }  ksort($arr2);  foreach ($arr2 as $id => &$val) {     $parent = $val['parent'];     if ($parent == 0) {         continue;     }     $arr2[$parent]['children'][$id] = &$val; }  function flattenArrayByChildren($arr) {     foreach ($arr as $id => $val) {         if (isset($val['children'])) {             $temp = flattenArrayByChildren($val['children']);             unset($val['children']);             $out[$id] = $val;             $out = $out + $temp;         } else {             $out[$id] = $val;         }     }     return $out; }  $arr2 = array(1 => $arr2[1]);  $out = flattenArrayByChildren($arr2);  var_dump($out); 

If you absolutely want to save the key, you can just add that to the $val in the first foreach, and retrieve it in the recursive function flattenArrayByChildren and use as key.

</div
 
 
     
     
0
 
vote
vote
La mejor respuesta
 

Resuelva el problema: hice dos funciones simples. Espero que otras personas también puedan usar esto:

  class data_comp {     var $fetched_tree = array();      function tree_fetch($parent = 0)     {         $query = 'SELECT node.id, node.name, node.parent, (COUNT(parent.name) - 1) AS depth FROM test_competence AS node, test_competence AS parent WHERE node.lft BETWEEN parent.lft AND parent.rgt GROUP BY node.name ORDER BY node.name';         $result = mysql_query($query) or die(mysql_error());         $tree = array();          while($data = mysql_fetch_assoc($result))         {             $tree[$data['parent']][$data['id']] = array('name' => $data['name'], 'depth' => $data['depth']);         }          $this->tree_print($tree, $parent);     }      function tree_print($tree, $parent)     {         foreach($tree[$parent] as $id => $value)         {             $this->fetched_tree[] = array('id' => $id, 'name' => $value['name'], 'depth' => $value['depth']);              if(isset($tree[$id]) && is_array($tree[$id]))             {                 $this->tree_print($tree, $id);             }         }     } }   

Gracias por su tiempo. Cualquier mejoras son más que bienvenidas.

 

Problem solved - I made two simple functions. I hope other people could have use of this as well:

class data_comp {     var $fetched_tree = array();      function tree_fetch($parent = 0)     {         $query = 'SELECT node.id, node.name, node.parent, (COUNT(parent.name) - 1) AS depth FROM test_competence AS node, test_competence AS parent WHERE node.lft BETWEEN parent.lft AND parent.rgt GROUP BY node.name ORDER BY node.name';         $result = mysql_query($query) or die(mysql_error());         $tree = array();          while($data = mysql_fetch_assoc($result))         {             $tree[$data['parent']][$data['id']] = array('name' => $data['name'], 'depth' => $data['depth']);         }          $this->tree_print($tree, $parent);     }      function tree_print($tree, $parent)     {         foreach($tree[$parent] as $id => $value)         {             $this->fetched_tree[] = array('id' => $id, 'name' => $value['name'], 'depth' => $value['depth']);              if(isset($tree[$id]) && is_array($tree[$id]))             {                 $this->tree_print($tree, $id);             }         }     } } 

Thank you for your time. Any improvements are more than welcome.

</div
 
 

Relacionados problema

4  PHP: Ordenar una matriz  ( Php sort an array ) 
Tengo una matriz con datos de una tabla MySQL en un modelo establecido anidado, me gustaría ser ordenado, no solo alfabético, sino también con los nodos infan...

1  ¿Cómo voy a hacer un contenido web de enlace en una base de datos con un modelo establecido anidado?  ( How do i go about link web content in a database with a nested set model ) 
Mi tabla establecida anidada es la siguiente. create table depts ( id int identity(0, 1) primary key , lft int , rgt int , name nvarchar(60) ...

1  Coincide con todos los personajes en grupo, excepto por la primera y la última ocurrencia  ( Match all characters in group except for first and last occurrence ) 
Di que solicito parent/child/child/page-name en mi navegador. Quiero extraer el padre, los niños, así como el nombre de la página. Aquí están las expre...

6  Buscando la mejor clase de conjuntos de PHP (clase excluida)  ( Searching for the best php nested sets class pear class excluded ) 
Estoy buscando una clase de conjuntos anidados de PHP (con MySQL) con todas las funciones necesarias. Por ejemplo: createleftnode, createrightnode, createro...

25  Mover el nodo en conjunto anidado  ( Move node in nested set ) 
Necesito una consulta de MySQL que mueva un nodo y todos sus hijos dentro de un conjunto anidado. Encontré este sitio , pero esa función parece tan ilógica -...

1  ¿Cómo crear una lista de selección dinámica con forma simple y increíble conjunto anidado en rieles 3.1?  ( How to create a dynamic select list using simple form and awesome nested set in ) 
¿Podría alguien explicar cómo crear una selección desplegable generada dinámicamente que muestra etiquetas de nombre al visitante web y escribe el ID correspo...

1  PHP: Ordenar datos de conjuntos anidados  ( Php sort data from nested sets ) 
Actualmente estamos construyendo un sitio web con una tabla MySQL categorizada que contiene varias competencias, y notamos que el modelo establecido anidado s...

2  Obtención de doctrina anidadizada con una consulta  ( Fetching doctrine nested set with one query ) 
Estoy buscando una manera de buscar un conjunto anidado en una consulta de DB. refs/pulls/1/merge7 Entonces, en total obtengo tantas consultas como cate...

0  Construye menú dinámico usando conjuntos anidados  ( Build dynamic menu using nested sets ) 
Estoy tratando de construir un menú dinámico en mi PHP CMS; Las páginas / categorías se organizan utilizando el modelo de conjuntos anidados. Árbol completo...

1  Disparadores: lista de adyacencia a un conjunto anidado  ( Triggers adjacency list to a nested set ) 
Tengo una lista de adyacencia en un sistema heredado que me gustaría consultar recursivamente (necesidad de obtener subtotales, etc.). ¿Puedo hacer un gatil...




© 2022 respuesta.top Reservados todos los derechos. Centro de preguntas y respuestas reservados todos los derechos