Display all data from an API in PHP - php

I want to display all data I want from Matomo API but I can only display them one by one
I don't know if I should do a for loop and where or how.
My code :
<?php
include 'TabMetrique.php';
$token_auth = '*********';
getMetrique($metrique);
$url = "http://localhost/matomo/";
$url .= "?module=API&method=".getMetrique($metrique)."&idSite=1";
$url .= "&period=month&date=2022-05-14";
$url .= "&format=JSON";
$url .= "&token_auth=$token_auth";
$fetched = file_get_contents($url);
$content = json_decode($fetched,true);
// case error
if (!$content) {
print("No data found");
}
else {
print("<h1>Métrique Matomo</h1>\n");
foreach ($content as $row) {
if ($content == $row){
$contentMetrique = htmlspecialchars($row["label"], ENT_QUOTES, 'UTF-8'); // à changer pour afficher toute les métrique
$hits = $row['nb_visits'];
print("<b>$contentMetrique</b> ($hits visits)<br>\n");
}else{
print("$row<b> action or visit</b>");
}
}
}
?>
My IF condition doesn't work but that's not a problem at the moment
And TabMetrique.php :
<?php
$metrique [0] = 'DevicesDetection.getModel'; // appareil utilisé
$metrique [1] = 'UserCountry.getCountry'; // Pays
$metrique [2] = 'UserCountry.getContinent'; //continent
$metrique [3] = 'UserCountry.getRegion'; // Region
$metrique [4] = 'UserCountry.getCity'; // Ville
$metrique [5] = 'UserId.getUsers'; // recupérer les UsersID
$metrique [6] = 'UserLanguage.getLanguage'; // Langue
$metrique [7] = 'VisitFrequency.get'; // Visiteur récurrent
$metrique [8] = 'VisitsSummary.get';
$metrique [9] = 'VisitsSummary.getVisits'; //visiteur
$metrique [10] = 'VisitsSummary.getUniqueVisitors'; // visiteur unique
function getMetrique($metrique){
return $metrique[9];
}
?>
someone can help me ? thx

Well first remove the function it is unnecessary, all you need is an array and then process it with a forech loop.
code TabMetrique.php
<?php
$metrique[0] = 'DevicesDetection.getModel'; // appareil utilisé
$metrique[1] = 'UserCountry.getCountry'; // Pays
$metrique[2] = 'UserCountry.getContinent'; //continent
$metrique[3] = 'UserCountry.getRegion'; // Region
$metrique[4] = 'UserCountry.getCity'; // Ville
$metrique[5] = 'UserId.getUsers'; // recupérer les UsersID
$metrique[6] = 'UserLanguage.getLanguage'; // Langue
$metrique[7] = 'VisitFrequency.get'; // Visiteur récurrent
$metrique[8] = 'VisitsSummary.get';
$metrique[9] = 'VisitsSummary.getVisits'; //visiteur
$metrique[10] = 'VisitsSummary.getUniqueVisitors'; // visiteur unique
?>
Now a simple foreach loop to control getting the names from the metrique array
<?php
include 'TabMetrique.php';
$token_auth = '*********';
$url = "http://localhost/matomo/?";
$url .= "period=month&date=2022-05-14";
$url .= "&format=JSON&module=API";
$url .= "&token_auth=$token_auth&idSite=1";
foreach ($metrique as $metric) {
//get static part of the url and add dynamic bit to it
// note i moved the dynamic part to be last, that should not matter to the api
$u = $url . "&method=$metric";
$content = json_decode(file_get_contents($u), true);
// case error
if (!$content) {
print("No data found");
} else {
print("<h1>Métrique Matomo</h1>\n");
foreach ($content as $row) {
if ($content == $row){
$contentMetrique = htmlspecialchars($row["label"], ENT_QUOTES, 'UTF-8'); // à changer pour afficher toute les métrique
$hits = $row['nb_visits'];
print("<b>$contentMetrique</b> ($hits visits)<br>\n");
}else{
print("$row<b> action or visit</b>");
}
}
}
}

Related

Modify an array with values from mysql table in php

I've this json call that is working fine: (just look at the $categorias array)
$query_tienda = $mysqli->query("SELECT * FROM tiendas");
$resultado_tienda = mysqli_fetch_assoc($query_tienda);
$nombre_tienda= $resultado_tienda['nombre'];
$action = (isset($_REQUEST['action'])&& $_REQUEST['action'] !=NULL)?$_REQUEST['action']:'';
if($action == 'ajax'){
include("conexion_all.php");//Contiene los datos de conexion a la base de datos
$periodo=intval($_REQUEST['periodo']);
$txt_mes=array( "1"=>"Ene","2"=>"Feb","3"=>"Mar","4"=>"Abr","5"=>"May","6"=>"Jun",
"7"=>"Jul", "8"=>"Ago","9"=>"Sep","10"=>"Oct","11"=>"Nov", "12"=>"Dic"
);//Arreglo que contiene las abreviaturas de los meses del año
$categorias []= array('Mes','Name1','Name2','Name3','Name4');
for ($inicio = 1; $inicio <= 12; $inicio++) {
$mes=$txt_mes[$inicio];//Obtengo la abreviatura del mes
$tienda_1=monto('1',$inicio,$periodo);//Obtengo ingresos de la tienda
$tienda_2=monto('2',$inicio,$periodo);
$tienda_3=monto('3',$inicio,$periodo);
$tienda_4=monto('4',$inicio,$periodo);
$categorias []= array($mes,$tienda_1,$tienda_2,$tienda_3,$tienda_4);//Agrego elementos al arreglo
}
echo json_encode( ($categorias) );//Convierto el arreglo a formato json
}
And need to change that part with something like this:
$categorias = array('Mes');
while ($contador = mysqli_fetch_array($query_tienda)) {
$categorias [] = $contador['name'];
}
To achieve the same result. I've trie diferent ways with no result, like:
$categorias = array('Mes');
while($r = mysqli_fetch_array($query_tienda) {
$row = array();
$row = array($r['nombre']);
array_push($categorias,$row);
unset($row);
}
Thanks for your help.
UPDATED: Finally find a solution:
$query_tienda = $mysqli->query("SELECT nombre FROM tiendas");
$cat = "Mes";
while ($row = mysqli_fetch_array($query_tienda)){
$cat .= ','.$row['nombre'];
$row++;
}
$categorias []= explode(',', $cat);
Thanks for all!!!
Updated and solved.
$query_tienda = $mysqli->query("SELECT nombre FROM tiendas");
$cat = "Mes";
while ($row = mysqli_fetch_array($query_tienda)){
$cat .= ','.$row['nombre'];
$row++;
}
$categorias []= explode(',', $cat);

OPENCART APP -> Customer Orders not being bound to Customer

Customer Orders not being bound to Customer
Postby DrFeeling » Mon Jun 01, 2015 4:05 pm
Good Afternoon peeps, I'm currently developping a mobile app for opencart that will bridge both tecnologies.
Most of the stuff is already active but I have a problem regarding order histories.
So, when you purchase something, through the main site, the default template of opencart, it generates a order history, that you can see through the website (my orders) or through the admin page.
My problem is that, whenever someone purchases something from the app, the orders of that costumer arent uptaded.
Though they appear in the main admin window (the dashboard) , once you go to customer (sales -> customers -> customers) the order made by the app isnt listed in the myOrders part of that customer, making both the "my previous orders" and the order of that customer inexistent in that place, but they appear in the dashboard and the notification email is foward to the customer
Please help me, and thanks for the support :D
Only order 261 (which was made in the website) is bounded to its customer, the others arent, as you can see in the pic below
AM I missing a parameter or a validation when the checkout process happens?
http://s16.postimg.org/y2h9rg5fp/image.jpg
EDIT: My code to create a order:
public function end_order() {
if ($this->customer->isLogged() == true){
$data= array();
$datap = array();
$this->load->model('account/customer');
$this->load->model('quickcheckout/order');
$this->load->model('checkout/order');
$myArray = $_POST["formData"];
$treatedArray = array();
foreach($myArray as $value) {
$treatedArray[$value['name']] = $value['value'];
}
$email = $_POST["email"];
$delivery = $_POST["deladdress"];
$delivery = array_shift($delivery); // sobe um nivel as posiçoes do array, em vez de usar $array[0]['bla'] , usasse so $array['bla']
$data2 = array();
$data2 = $this->model_account_customer->getCustomerByEmail($email);
$Method = $_POST["PayMethod"];
$TotalCheckout = $_POST["TotalCheck"];
$IP = $_POST["IP"];
$Agent = $_POST["User"];
$Products = $_POST["Prod"];
$length = count($Products);
for ($i = 0; $i < $length; $i++) {
(int)$datap[$i]['product_id'] = $Products[$i]['Id'];
$datap[$i]['name'] = $Products[$i]['Name'];
$datap[$i]['model'] = $Products[$i]['modelo'];
(int)$datap[$i]['quantity'] = $Products[$i]['NItems'];
$datap[$i]['price'] = $Products[$i]['Preco'];
$datap[$i]['total'] = $Products[$i]['Total'];
$datap[$i]['tax'] = 0; //$Products[$i]['Tax'];
(int)$datap[$i]['reward'] = 0; //$Products[$i]['Reward'];
}
$url = $myurl;
$data['invoice_prefix'] = $this->config->get('config_invoice_prefix');
$data['store_id'] = $this->config->get('config_store_id');
$data['store_name'] = "Loja Teste";
$data['store_url'] = $url;
$data['firstname'] = $data2['firstname'] ;
$data['lastname'] = $data2['lastname'];
$data['email'] = $data2['email'];
$data['telephone'] = $data2['telephone'];
$data['fax'] = $data2['fax'];
$data['payment_firstname'] = $delivery['firstname'];
$data['payment_lastname'] = $delivery['lastname'];
$data['payment_company'] = $delivery['company'];
$data['payment_company_id'] = $delivery['company_id'];;
$data['tax_id'] = $delivery['tax_id'];
$data['payment_address_1'] = $delivery['address_1'];
$data['payment_address_2'] = $delivery['address_2'];
$data['payment_city'] = $delivery['city'];
$data['payment_postcode'] = $delivery['postcode'];
$data['payment_country'] = $delivery['country'];
$data['payment_country_id'] = $delivery['country_id'];
$data['payment_zone'] = $delivery['zone'];
$data['payment_zone_id'] = $delivery['zone_id'];
$data['payment_method'] = "Cash On Delivery";
$data['payment_code'] = 1;
$data['total'] = $TotalCheckout;
//NOTA: esta duas variaveis abaixo servem para tratar dos preços, alterar depois para quando a loja tiver opçoes de escolher preços
$data['language_id'] = (int)$this->config->get('config_language_id');
$data['accept_language'] = $this->request->server['HTTP_ACCEPT_LANGUAGE'];
$data['currency_id'] = (int)2;
$data['currency_code'] = "USD";
$data['currency_value'] = (float)1.00000000;
$data['ip'] = $IP;
$data['forwarded_ip'] = $IP;
$data['user_agent'] = $Agent;
$data['products'] = $datap;
(int)$order = $this->model_checkout_order->addOrder($data);
$this->model_checkout_order->confirm($order, 1 , $comment = '', $notify = false);
echo ("teste");
}
}

Calling a php variable that is within an if

Can someone explain me why I cannot call a var that is set inside an if? And how to call it? I don't understand why this come empty.
I need the vars $workshop_manha and $workshop_tarde bring the values that comes from the DB.
CODE
$id = implode(",", $id);
$sql_consulta = mysql_query("SELECT * FROM pessoa WHERE id IN($id)")
or die (mysql_error());
$linha = mysql_fetch_array($sql_consulta);
$id = $linha['id'];
$nome = $linha['nome'];
$opcoes = $linha['opcoes'];
$opcoes2 = explode(":", $opcoes);
$opcoes3 = explode("+", $opcoes2[1]);
$opcao_congresso = $opcoes3[0]; // Option Congress
if(!empty($opcoes2[2])){
$opcoes4 = explode("+", $opcoes2[2]);
$pre_workshop_manha = $opcoes4[0]; // Workshop Morning Option
if($pre_workshop_manha == 'Paul Gilbert'){
$workshop_manha = "Paul Gilbert: Introdução à Terapia Focada na Compaixão e Técnicas";
}
if($pre_workshop_manha == 'Daniel Rijo'){
$workshop_manha = "Daniel Rijo: Os Esquemas do terapeuta e a relação terapêutica com doentes com patologia de personalidade";
}
if($pre_workshop_manha == 'Maria Salvador'){
$workshop_manha = "Maria do Céu Salvador: Os Esquemas do terapeuta e a relação terapêutica com doentes com patologia de personalidade";
}
}
if(!empty($opcoes2[3])){
$opcoes5 = explode("+", $opcoes2[3]);
$pre_workshop_tarde = $opcoes5[0]; // Worhshop Afternoon Option
if($pre_workshop_tarde == 'Donna Sudak'){
$workshop_tarde = "Donna Sudak: Quando as coisas ficam difíceis: Aplicações práticas da Terapia Comportamental Dialética";
}
if($pre_workshop_tarde == 'Philipp Kendall'){
$workshop_tarde = "Philipp Kendall: Estratégias dentro de tratamentos empiricamente baseados em evidências para jovens com ansiedade";
}
}
echo "Work manhã: ".$workshop_manha; //is coming empty :(
echo "Work tarde: ".$workshop_tarde; //is coming empty :(
That's because $workshop_manha and $workshop_tarde are not defined before the if statement.
Put this before the if statement:
$workshop_manha = '';
$workshop_tarde = '';
You can use them as an array().
Empty the values at the beginning :
$workshop_manha=array();
$workshop_tarde=array();
Than use the values as :
$workshop_manha[] = "Paul Gilbert: Introdução à Terapia Focada na Compaixão e Técnicas";
Display them as below :
if(!empty($workshop_manha)) {
foreach ($workshop_manha as $manha) {
echo "$manha <br />";
}
}
if(!empty($workshop_tarde)) {
foreach ($workshop_tarde as $tarde) {
echo "$tarde <br />";
}
}

PHP How to replace specific string from an URL

I'm bulding a multilanguage web in PHP, i have the class for the language change, i can do it by setting the $_SESSION or just by changing the lang value in the url, i'm working with rewrite mod for apache so this is how my URL looks like:
http://www.server.com/en/something/else/to/do
I have a function that displays an upper bar in the entire site, and in that bar i have the flags for language change.
I use this class to change Language:
class IDIOMAS {
private $UserLng;
private $langSelected;
public $lang = array();
public function __construct($userLanguage){
$this->UserLng = $userLanguage;
}
public function userLanguage(){
switch($this->UserLng){
case "en":
$lang['PAGE_TITLE'] = TITULO().' | Breaking news, World news, Opinion';
// Menu
$lang['MENU_LOGIN'] = 'Login';
$lang['MENU_SIGNUP'] = 'Sign up';
$lang['MENU_LOGOUT'] = 'Logout';
$lang['MENU_SEARCH'] = 'Search';
//Suscripciones
$lang['SUBSCRIBE_SUCCESS'] = "¡Thank you, we'll let you know when we become online!";
$lang['SUBSCRIBE_EMAIL_REGISTERED'] = 'This e-mail is already registered';
$lang['SUBSCRIBE_EMAIL_INVALID'] = 'The e-mail you entered is invalid';
$lang['SUBSCRIBE_EMAIL_WRITE'] = 'You must write down your e-mail';
$lang['SUBSCRIBE_TITLE'] = '¡Subscribe!';
$lang['SUBSCRIBE_CONTENT'] = 'And be the first to read the best articles in the web';
$lang['SUBSCRIBE_PLACEHOLDER'] = 'Enter your E-mail';
$lang['SUBSCRIBE_SEND'] = 'SEND';
//LOGIN
$lang['LOGIN_TITLE'] = 'Please Login to your account';
$lang['LOGIN_USER'] = 'User';
$lang['LOGIN_PASSWORD'] = 'Password';
$lang['LOGIN_ERROR'] = '¡User and/or password invalid!';
//REGISTER
$lang['REGISTER_NAME'] = 'Please write your name';
$lang['REGISTER_LAST_NAME'] = 'Please write your last name';
$lang['REGISTER_EMAIL'] = 'Write your E-mail';
$lang['REGISTER_CITY'] = 'Enter your City name';
$lang['REGISTER_COUNTRY'] = '¿Where are you from?';
$lang['REGISTER_ZIP_CODE'] = 'Enter your ZIP Code';
$lang['REGISTER_DATE_BIRTH'] = 'Please enter your date of birth';
return $lang;
break;
case "es":
$lang['PAGE_TITLE'] = TITULO().' | Noticias de última hora, Noticias mundiales, Matrices de opinión';
// Menu
$lang['MENU_LOGIN'] = 'Entrar';
$lang['MENU_SIGNUP'] = 'Registrarse';
$lang['MENU_LOGOUT'] = 'Salir';
$lang['MENU_SEARCH'] = 'Buscar';
//Suscripciones
$lang['SUBSCRIBE_SUCCESS'] = "¡Gracias, te avisaremos cuando estemos online!";
$lang['SUBSCRIBE_EMAIL_REGISTERED'] = 'Este email ya se encuentra registrado';
$lang['SUBSCRIBE_EMAIL_INVALID'] = 'El correo que introdujiste es inválido';
$lang['SUBSCRIBE_EMAIL_WRITE'] = 'Debes escribir tu email';
$lang['SUBSCRIBE_TITLE'] = '¡Suscríbete!';
$lang['SUBSCRIBE_CONTENT'] = 'Y se el primero en leer las mejores noticias y artículos en la web';
$lang['SUBSCRIBE_PLACEHOLDER'] = 'Introduce tu E-mail';
$lang['SUBSCRIBE_SEND'] = 'Enviar';
//LOGIN
$lang['LOGIN_TITLE'] = 'Por favor inicia sesión en tu cuenta';
$lang['LOGIN_USER'] = 'Usuario';
$lang['LOGIN_PASSWORD'] = 'Clave';
$lang['LOGIN_ERROR'] = '¡Usuario y/o clave incorrectos!';
//REGISTRO
$lang['REGISTRO_NOMBRE'] = 'Por favor introduce tu nombre';
$lang['REGISTRO_APELLIDO'] = 'Por favor introduce tu apellido';
$lang['REGISTRO_CORREO'] = 'Introduce tu correo electrónico';
$lang['REGISTRO_CIUDAD'] = 'Introduce el nombre de tu ciudad';
$lang['REGISTRO_PAIS'] = '¿De donde eres?';
$lang['REGISTRO_CODIGO_POSTAL'] = 'Introduce tu Código Postal';
$lang['REGISTRO_FECHA_NAC'] = 'Por favor introduce tu fecha de nacimiento';
return $lang;
break;
}
}
}
I use this class with this code:
$language = new IDIOMAS($lang);
$langArray = array();
$langArray = $language->userLanguage();
And set the language like this:
if (!isset($_SESSION['idioma'])){
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
$_SESSION['idioma'] = $lang;
}else{
$lang = $_SESSION['idioma'];
}
if(isset($_GET['lang']) && in_array($_GET['lang'], array('en', 'es'))){
$_SESSION['idioma'] = $_GET['lang'];
$lang = $_SESSION['idioma'];
}
Now the issue i have is that when i try to change language of the page i'm on, i mean, if i'm located in www.server.com and nothing else i need to put the /es or /en at the end for changing the lang, but if i'm in www.server.com/es/something/else/to/do i need to change specificallly the /es parameter.
I have a function to get the current url for redirections when being logged or register.
function getUrl() {
$url = #( $_SERVER["HTTPS"] != 'on' ) ? 'http://'.$_SERVER["SERVER_NAME"] : 'https://'.$_SERVER["SERVER_NAME"];
$url .= $_SERVER["REQUEST_URI"];
return $url;
}
I was trying to change the lang value inside that function with no success,
Really appreciate any help
Here is a simple solution that I would do. I don't know if its exactly what you'll want to use:
// Find the first forward slash location
$pos1 = strpos($url,'/'); // The whole URL
// You only need this next line if your language codes are different sizes
// If they are always 2 then can alter the code to not use it
$pos2 = strpos($url,'/',$pos1); // Now find the second by offsetting
$base = substr($url,0,$pos1); // Get domain name half
$end = substr($url,$pos2); // Get everything after language area
// Now from the function return the result
$val = $base.'/'.$newlang.'/'.$end;
return $val;
You may need to add or subtract 1 on the $pos to get the right values returned, like so:
$pos2 = strpos($url,'/',$pos1+1); // In case its finding the wrong slash
$base = substr($url,0,$pos1-1); // In case its returning the slash
$end = substr($url,$pos2+1); // In case its return the slash
Please tweak and test this, it is only the concept in action, I have not tested this snip-it.
Finally i got it by modifying the getUrl function to this:
function getUrl($newlang) {
$url = #( $_SERVER["HTTPS"] != 'on' ) ? 'http://'.$_SERVER["SERVER_NAME"] : 'https://'.$_SERVER["SERVER_NAME"];
$url .= $_SERVER["REQUEST_URI"];
$substr = substr($url,27,3);
$base = substr($url,0,28);
$resto = substr($url,31,1000);
$newUrl = $base.$newlang."/".$resto;
return $newUrl;
}
and calling the function like this getUrl("en") or getUrl("es");
Maybe this can be usefull for someone else.

Return the loop at initialization of the foreach

I want to return at the init of the loop and when the count of array is 10, I need to print it out.
I am not sure if it is possible because, the return is out of the foreach loop.
Thanks in advice.
This is my current code:
<?php
error_reporting(0);
include_once('include.php');
$link=connect_db();
//butta in un array tutti i forecast e usa print_r(array_count_values($array));
//fai un foreach che per ogni previsione fa partire una query con variabi $limit che è il parametro di ff.previsione e il LIMIT 0,$limit
$get_values = "select previsione from forecast where data='2014-05-30'";
$res_values = mysql_query($get_values,$link);
$arr_vals = array();
while( $values = mysql_fetch_assoc($res_values) ) {
array_push($arr_vals, $values['previsione']);
}
$new_array = array();
foreach ( $arr_vals as $key => $value ) {
$limit = $value;
$sel = "select min(op.cognome) as cogg,
op.nome,
op.cognome,
op.ore_giornaliere_time,
ff.ora,
ff.previsione
from
operatori op
join
turni_preconf tp on tp.tot_ore = op.ore_giornaliere
join
forecast ff on tp.inizio=ff.ora
where
ff.data='2014-05-30' and ff.previsione=$limit
group by op.cognome
order by rand()
limit 0,$limit";
$res_sel=mysql_query($sel,$link);
while( $er = mysql_fetch_array($res_sel) ) {
echo $er['nome'].' '.$er['cognome'].': '.remove_sec($er['ora']).'/'.sumatra($er['ora'], $er['ore_giornaliere_time']).'<br>';
$nomecognome = $er['nome'].$er['cognome'];
$orario = $er['ora'].'-'.sumatra($er['ora'], $er['ore_giornaliere_time']);
array_push($new_array, array($nomecognome => $orario));
//$new_array[$nomecognome] = $orario;
}
}
var_dump($new_array);
echo'<br>';
$array2 = call_user_func_array('array_merge', $new_array);
echo count($array2);
if(count($array2) == 10){
var_dump($array2);
}
if(count($array2) != 10){
//RETURN FROM ??? HELP...
}
//butta nome cognome ora_inizio/ora_fine nel seguente modo [nomecognome]=>"ora_inizio-ora_fine" e rimuovi le chiavi duplicate preservando l'ordine
?>
Im still not realy sure what you mean, but it sounds like (for me) that you try to print out the array after it has exactly a length of 10. Else you want to run the foreach loop again until there are 10 elements in the array?
If this is what you mean then i would consider to put your foreach in a do{}while() loop.
Similar to this one:
Edit: [UNTESTED not sure if it works properly]
<?php
//some code
do{
//code that should repeat until arraylength == 10 goes in here
foreach(...)
.
.
.
}while( count($array2) == 10 );
//no need for a second if statment,
//cause it only gets executet if we get out of the loop.
var_dump($array2);
//some other code that gets executed
.
.
.
?>
And now on your code:
<?php
error_reporting(0);
include_once('include.php');
$link=connect_db();
//butta in un array tutti i forecast e usa print_r(array_count_values($array));
//fai un foreach che per ogni previsione fa partire una query con variabi $limit che è il parametro di ff.previsione e il LIMIT 0,$limit
$get_values = "select previsione from forecast where data='2014-05-30'";
$res_values = mysql_query($get_values,$link);
$arr_vals = array();
while( $values = mysql_fetch_assoc($res_values) ) {
array_push($arr_vals, $values['previsione']);
}
// START REPEAT until count($array2) == 10
do{
$new_array = array();
foreach ( $arr_vals as $key => $value ) {
$limit = $value;
$sel = "select min(op.cognome) as cogg,
op.nome,
op.cognome,
op.ore_giornaliere_time,
ff.ora,
ff.previsione
from
operatori op
join
turni_preconf tp on tp.tot_ore = op.ore_giornaliere
join
forecast ff on tp.inizio=ff.ora
where
ff.data='2014-05-30' and ff.previsione=$limit
group by op.cognome
order by rand()
limit 0,$limit";
$res_sel = mysql_query($sel,$link);
while( $er = mysql_fetch_array($res_sel) ) {
echo $er['nome'].' '.$er['cognome'].': '.remove_sec($er['ora']).'/'.sumatra($er['ora'], $er['ore_giornaliere_time']).'<br>';
$nomecognome = $er['nome'].$er['cognome'];
$orario = $er['ora'].'-'.sumatra($er['ora'], $er['ore_giornaliere_time']);
array_push($new_array, array($nomecognome => $orario));
//$new_array[$nomecognome] = $orario;
}
}
var_dump($new_array);
echo'<br>';
$array2 = call_user_func_array('array_merge', $new_array);
echo count($array2);
}while(count($array2) != 10) //END OF REPEAT
var_dump($array2);
//butta nome cognome ora_inizio/ora_fine nel seguente modo [nomecognome]=>"ora_inizio-ora_fine" e rimuovi le chiavi duplicate preservando l'ordine
?>
Hope this helps.

Categories