Tri d'un tableau bi-dimensionnel

  • Par: jack
  • Le: 28.03.2009 16:35:38
  • Dans: PHP
Voici le code permettant de trier un tableau comportant plusieurs colonnes en fonction d'une autre que la première.

<?php

// Initialisation d'un tableau de 2 colonnes

$tab[0]=array('mot'=> 'exemple', 'traduction' => 'example');

$tab[1]=array('mot'=> 'chien', 'traduction' => 'dog');

$tab[2]=array('mot'=> 'chat', 'traduction' => 'cat');

// Tri du tableau en fonction de la colonne traduction

asort($tab['traduction']);

// Copie dans un tableau nouveau tableau

// afin d'obtenir un tableau avec des index propres

$final=array();

$i=0;

foreach($tab['traduction'] as $cle => $valeur) {

$final['mot'][$i]=$tab['mot'][$cle];

$final['traduction'][$i]=$tab['traduction'][$cle];

$i++;

}

?>

Voila votre tableau trié en fonction de la seconde colonne. Attention toutefois, le tri est case-sensitive. Ce qui peut conduire à des résultats surprenants.