Bonjour,
Pour mes besoins personnels, j’ai créé une fonction permettant de récupérer des valeurs stockées dans une variable de type tableau.
La fonction est à inscrire dans le fichier user.function.class.php .
public static function readfromArray($_variable = '', $_path = '') {
// Suppression des caractères indésirables
// transforme "toto"."titi" ou 'toto'.'titi' ou [toto][titi]
// ou ["toto"]["titi"] ... en toto.titi
$_variable = preg_replace('/([\"\']|^[\[]|[\]]$)/', '', $_variable);
$_path = preg_replace('/([\"\']|^[\[]|[\]]$)/', '', $_path);
$_path = preg_replace('/(\]\[)/', '.', $_path);
// Récupère le tableau stocké dans la variable Jeedom indiquée
$dataStore = dataStore::byTypeLinkIdKey('scenario', -1, $_variable);
if (is_object($dataStore)) {
$array = $dataStore->getValue();
}
// Découpe la chaine $_path en un tableau
// contenant les coordonnées de la valeur à récupérer
$keys = explode('.',$_path);
$text = '';
foreach ($keys as $key) {
$text = $text.'['.$key.']';
}
// Récupère la valeur
eval('$value = $array'.$text.';');
if ($_path == 'debug') {
return var_export($array,true);
}
else
{
return $_path.' '.$value;
}
}
Ensuite, on peut utiliser la fonction readfromArray(MaVariable,index) pour lire le tableau.
Par exemple, j’utilise ce script php dans un scenario qui récupère la météo et stocke les infos dans une variable tableau.
$apiKey = "1234567890abcdef";
$cityId = "2643743";
$OWMapUrl = "http://api.openweathermap.org/data/2.5/weather?id=" . $cityId . "&lang=fr&units=metric&APPID=" . $apiKey;
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $OWMapUrl);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);
$weatherdata = json_decode($response,true);
$scenario->setLog($response);
$scenario->setData('Weather',$weatherdata);
Dans mes scenarios, je peux ensuite appeler les valeurs de la manière suivante :
- Rafales de vent : readfromArray(Weather,wind.gust)
- Température : readfromArray(Weather,main.temp)
Faites en bon usage !
Patrice