Techno-magis

Transformer un « array » en chaîne PHP

Friday 22th November 2013

C'est très con, mais j'avais besoin de générer un tableau PHP en PHP pour le stocker et pouvoir l'utiliser plus tard. J'aurais pu passer par du XML ou du JSON, mais quitte à lire du code dans un fichier autant faire un include() en PHP, comme ça il n'y a aucun traitement à faire par la suite.

CODE:

$mon_tableau = array(
	'clé1_n1' => 'val1_n1',
	'clé2_n1' => 'val2_n1',	
	'clé3_n1' => array(
		'clé1_n2' => 'val1_n2'
	)
);

Le tableau est indenté pour être plus facile à lire.

Voilà le code pour générer le tableau sous forme de chaîne comme ci-dessus. C'est sans limites de niveaux. Ça merdera certainement s'il y a des objets :

CODE:

/** retour à la ligne */
define('N', "\n");
/** tabulation */
define('T', "\t");
 
/**
 * retourne un tableau multidimensionnel sous forme « texte PHP » et en arbre
 * @param string $nom Nom du tableau : $nom = array();
 * @param array $tab	Tableau à sérialiser en code PHP. 
 * @return string le tableau sous forme de texte PHP ${nom} = array(...);
 */ 
function array_tostring($nom, array $tab) {
	if (is_array($tab)) {
		return "\${$nom} = array (".N
			 . array_tostring_a_parse($tab)
			 . N.");";
	} else {
		return false;
	}
}
function array_tostring_parse(array $tab, $n = 1) {
	if (is_array($tab)) {
		$lv = array();
		$space = str_repeat (T, $n);
 
		foreach($tab as $key => $val) {
			$t = array_tostring_a_val($key)." => ";
			if (is_array($val)) {
				$t .= "array (".N.array_tostring_a_parse($val, $n+1).N.$space.")";
			} elseif ($val === true){
				$t .= 'true';
			} elseif ($val === false){
				$t .= 'false';
			} elseif ($val === null){
				$t .= 'null';
			} else {
				$t .= array_tostring_a_val($val);
			}
			$lv[] = $t;
		}		
		return $space.implode(",".N.$space, $lv);
	}
}
function array_tostring_val ($key) {
	return is_numeric($key) ? $key : "'".addqslashes($key, '"')."'";
}
 

Categories:
By Zéfling, the 22/11/2013 at 06:33:07
The ticket was read 364 times, with 1 comment posted.
👍 0 👎 0

1 comment posted

By Zéfling, the 07/03/2014 at 12:02:01
Avatar
Administrator

Mmm, je découvre que var_export() (natif) fait la même chose en mieux, j'ai l'impression.

L'homme est le plus inhumain des animaux.

Write a commentary