I have this code:
And this is my data structure:
totalMes Function:
function totalMes(){
//Genera un array con el total de cada mes
global $tickets;
$totales = ["juego" => '', "precioTicket" => 0, "cantidadTickets" => 0];
for ($i=0; $i < 12; $i++) {
foreach($tickets[$i] as $juegos){
foreach ($juegos as $key => $value){
$totales[$key] += $value;
$totalMes[$i] = $totales['precioTicket'] * $totales['cantidadTickets'];
}
$totales = ["juego" => '', "precioTicket" => 0, "cantidadTickets" => 0];
}
}
return $totalMes;
}
Now when I enter a new value to array tickets and then I call totalMes function. It accumulates me only the last value of the array tickets.
Example:
function ingresarJuego($mes, $juego, $precioTicket, $cantidadTickets){
global $tickets;
$juego = ["juego" => $juego, "precioTicket" => $precioTicket, "cantidadTickets" => $cantidadTickets];
array_push($tickets[$mes], $juego);
return $tickets;
}
This is my array totalMes, before entering a new record to array tickets:
Array
(
[0] => 100
[1] => 1886
[2] => 774
[3] => 720
[4] => 7719
[5] => 5238
[6] => 2430
[7] => 2736
[8] => 1080
[9] => 315
[10] => 621
[11] => 6536
)
Now if I enter a value in array tickets and then calculate totalMes again. it does not accumulate the values if the treads with the last record.
Array
(
[0] => 4 // When it should be 100 + 4
[1] => 1886
[2] => 774
[3] => 720
[4] => 7719
[5] => 5238
[6] => 2430
[7] => 2736
[8] => 1080
[9] => 315
[10] => 621
[11] => 6536
)
I don't understand well your questio but
Could be you need and add for the value
array_push($tickets[$mes],$tickets[$mes] + $juego);
Related
Array:
$ecodesAr = Array (
[0] => 1Z0-060
[1] => 98-375
[2] => 98-368
[3] => 98-367 )
for($k=0; $k<count($ecodesAr); $k++){
$arrayTB[$k] = $this->Functions->exam('title', $ecodesAr[$k]); }
Modal code:
public function exam($q, $d) {
$q = $this->db->where($q, $d)
->get('exams');
return $q->row();
}
Result:
Array (
[0] =>
[1] =>
[2] =>
[3] => stdClass Object ( [id] => 1091 [hot_exam] => 0 [top_exam] => 0 [category] => 114 [subcats] => 288 [slug] => 98-367 [sku] => OI5Ao [title] => 98-367 [name] => MTA Security Fundamentals [update] => 2021-09-16 [regular_price] => 130 [sale_price] => 59 [on_homepage] => 0 [on_request] => 0 [expired] => 0 [path_slug] => 98-367.pdf [questions] => 123 [demo_slug] => 98-367-demo.pdf [prc_price] => 65 [prc_demo] => 98-367-demo [prc_exam] => 98-367 [is_active] => 1 )
)
The First 3 values are skiped in the output and just the last value got, I want to all array data against values please help anyone!
$productsarry = Array (
[0] => Milk
[1] => Cream
[2] => Sugar
[3] => Yougert
);
for($k = 0; $k < count($productsarry); $k++) {
$arrayTB[$k] = query("select slug, qty, name, price from exams where title ='$ecode'")->row();
}
0I have an array ($dataArray) in the following format which is created from a csv file:
The CSV is processed as follows:
function csvstring_to_array($string, $separatorChar = ',', $enclosureChar = '"', $newlineChar = "\n") {
// #author: Klemen Nagode
$array = array();
$size = strlen($string);
$columnIndex = 0;
$rowIndex = 0;
$fieldValue="";
$isEnclosured = false;
for($i=0; $i<$size;$i++) {
$char = $string{$i};
$addChar = "";
if($isEnclosured) {
if($char==$enclosureChar) {
if($i+1<$size && $string{$i+1}==$enclosureChar){
// escaped char
$addChar=$char;
$i++; // dont check next char
}else{
$isEnclosured = false;
}
}else {
$addChar=$char;
}
}else {
if($char==$enclosureChar) {
$isEnclosured = true;
}else {
if($char==$separatorChar) {
$array[$rowIndex][$columnIndex] = $fieldValue;
$fieldValue="";
$columnIndex++;
}elseif($char==$newlineChar) {
echo $char;
$array[$rowIndex][$columnIndex] = $fieldValue;
$fieldValue="";
$columnIndex=0;
$rowIndex++;
}else {
$addChar=$char;
}
}
}
if($addChar!=""){
$fieldValue.=$addChar;
}
}
if($fieldValue) { // save last field
$array[$rowIndex][$columnIndex] = $fieldValue;
}
return $array;
}
$dataArray = csvstring_to_array( file_get_contents("ACS_MONTHLY_DUES - Jun 2020.csv"));
echo '<pre>';
print_r($dataArray);
echo '</pre>';
Array
(
[0] => Array
(
[0] => REGION
[1] => CENTER
[2] => SUBSCRIBER CODE
[3] => SUBSCRIBER_ID
[4] => SUBSCRIBERNAME
[5] => SUBSCRIBERPHONE
[6] => BOUQ
[7] => STB_NOS
[8] => LAST MONTH PAYMENT
[9] => AMOUNT_DUE
[10] => MINIMUM_RECHARGE
[11] => TOTAL_PAYABLE
[12] => EXPIRY_DATE
[13] => PAY_AMOUNT
[14] => CURRENT BALANCE
)
[1] => Array
(
[0] => XXX
[1] => XXX
[2] => UK91002970
[3] => 61610070
[4] => XXXXX
[5] => XXXXXX
[6] => UK FTA-1
[7] => 1
[8] => 0
[9] => 0
[10] => 221
[11] => 221
[12] => 08-06-2020
[13] => 0
[14] => 0
)
[2] => Array
(
[0] => XXXX
[1] => XXXXX
[2] => UK91002971
[3] => 61610217
[4] => XXXXXXX
[5] => XXXXXXX
[6] => UK FTA-1
[7] => 1
[8] => 0
[9] => 8
[10] => 243
[11] => 251
[12] => 06-06-2020
[13] => 0
[14] => 0
)
)
I need to insert it in my mysql DB using PDO. I tried the following and it is not working:
include_once('inc/connstring.inc.php');
$stmt = $conn->prepare("INSERT INTO customer(subscriber_code, subscriber_id, region,center,subscriber_name,subscriber_phone,package,stb_nos,last_month_payment,amount_due,minimum_recharge,total_payable,expiry_date,pay_amount,current_balance)
VALUES(:subscribercode, :subscriberid, :region,:center,:subscribername,:subscriberphone,:package,:stbnos,:lastmonthpayment,:amountdue,:minimumrecharge,:totalpayable,:expirydate,:payamount,:currentbalance)");
foreach($dataArray as $row) {
$stmt->execute(array(
':subscribercode' => $row['SUBSCRIBER CODE'],
':subscriberid' => $row['SUBSCRIBER_ID'],
':region' => $row['REGION'],
':center' => $row['CENTER'],
':subscribername' => $row['SUBSCRIBERNAME'],
':subscriberphone' => $row['SUBSCRIBERPHONE'],
':package' => $row['BOUQ'],
':stbnos' => $row['STB_NOS'],
':lastmonthpayment' => $row['LAST MONTH PAYMENT'],
':amountdue' => $row['AMOUNT_DUE'],
':minimumrecharge' =>$row['MINIMUM_RECHARGE'],
':totalpayable' => $row['TOTAL_PAYABLE'],
':expirydate' => $row['EXPIRY_DATE'],
':payamount' => $row['PAY_AMOUNT'],
':currentbalance' => $row['CURRENT BALANCE']));
}
It is not working. Invalid argument supplied for foreach()
What am i doing wrong?? Requesting help from php experts...
Thanks in advance.
update:
Solved myself. Changed code to convert CSV to an associative array and now everything works fine.
Array
(
[0] => Array
(
[REGION] => XXX
[CENTER] => XXXXX
[SUBSCRIBER CODE] =>UK91002970
[SUBSCRIBER_ID] => 61610070
[SUBSCRIBERNAME] => XXXXX
[SUBSCRIBERPHONE] => XXXXXXX
[BOUQ] => UK FTA-1
[STB_NOS] => 1
[LAST MONTH PAYMENT] => 0
[AMOUNT_DUE] => 0
[MINIMUM_RECHARGE] => 221
[TOTAL_PAYABLE] => 221
[EXPIRY_DATE] => 08-06-2020
[PAY_AMOUNT] => 0
[CURRENT BALANCE] => 0
)
Your array $dataArray contains this:
Array
(
[0] => Array
(
[0] => REGION
[1] => CENTER
[2] => SUBSCRIBER CODE
[3] => SUBSCRIBER_ID
[4] => SUBSCRIBERNAME
[5] => SUBSCRIBERPHONE
[6] => BOUQ
[7] => STB_NOS
[8] => LAST MONTH PAYMENT
[9] => AMOUNT_DUE
[10] => MINIMUM_RECHARGE
[11] => TOTAL_PAYABLE
[12] => EXPIRY_DATE
[13] => PAY_AMOUNT
[14] => CURRENT BALANCE
)
[1] => Array
(
[0] => XXX
[1] => XXX
[2] => UK91002970
[3] => 61610070
[4] => XXXXX
[5] => XXXXXX
[6] => UK FTA-1
[7] => 1
[8] => 0
[9] => 0
[10] => 221
[11] => 221
[12] => 08-06-2020
[13] => 0
[14] => 0
)
You try to apply values values into your SQL by using REGION, CENTER, SUBSRICBER CODE etc. but you're mixing up keys with values
This array does not include $row['REGION'], does not include $row['CENTER'] etc...
If you're doing like this:
foreach($dataArray as $row) {
$stmt->execute(array(
':subscribercode' => $row['SUBSCRIBER CODE'],
':subscriberid' => $row['SUBSCRIBER_ID'],
etc...
}
then the array $dataArray would have to look like this:
Array
(
['SUBSCRIBER CODE'] => {value}
['SUBSCRIBER_ID'] => {value}
['SUBSCRIBERNAME'] => {value}
etc
)
One solution would be if (if I understand the array structure correctly) to apply keys from second and further based on first elements values
Lets say we have this:
Array
(
[0] => Array
(
[0] => REGION
[1] => CENTER
[2] => SUBSCRIBER CODE
[3] => SUBSCRIBER_ID
)
[1] => Array
(
[0] => XXX
[1] => XXX
[2] => UK91002970
[3] => 61610070
)
[2] => Array
(
[0] => XXX
[1] => XXX
[2] => UK91002971
[3] => 61610217
)
[3] => Array
(
[0] => XXX
[1] => XXX
[2] => UK91002972
[3] => 61610218
)
)
then first element contains: ['REGION', 'CENTER', 'SUBSCRIBER CODE','SUBSCRIBER_ID']
and second to fourth element contains the actual values "mapped to region, center , subscriber code, subscriber id".
A solution would be:
$dataArray = [];
$dataArray[] = ['REGION', 'CENTER', 'SUBSCRIBER CODE','SUBSCRIBER_ID'];
$dataArray[] = ['XXX', 'XXX', 'UK91002970', '61610070'];
$dataArray[] = ['XXX', 'XXX', 'UK91002971', '61610217'];
$dataArray[] = ['XXX', 'XXX', 'UK91002972', '61610218'];
$keys_apply = array_values($dataArray[0]); //get all values of first item in array
$i = 0;
foreach($dataArray as $key=>$item) {
if ($i>0) { //skip first item
$index = 0; //We know that index are 0 and above we start with zero here and
//and add one for each iteration
foreach($item as &$ik) {
//create new item with mapped key-value from first item in array but with
//the same value ($ik)
$dataArray[$key][$keys_apply[$index]] = $ik;
//Unset removes $dataArray[1][0], [1][1], [1][2] etc.
unset($dataArray[$key][$index]);
//Next element in this inner array
$index++;
}
}
$i++;
}
You would then have:
Array
(
[0] => Array
(
[0] => REGION
[1] => CENTER
[2] => SUBSCRIBER CODE
[3] => SUBSCRIBER_ID
)
[1] => Array
(
[REGION] => XXX
[CENTER] => XXX
[SUBSCRIBER CODE] => UK91002970
[SUBSCRIBER_ID] => 61610070
)
[2] => Array
(
[REGION] => XXX
[CENTER] => XXX
[SUBSCRIBER CODE] => UK91002971
[SUBSCRIBER_ID] => 61610217
)
[3] => Array
(
[REGION] => XXX
[CENTER] => XXX
[SUBSCRIBER CODE] => UK91002972
[SUBSCRIBER_ID] => 61610218
)
)
And then your original
foreach($dataArray as $row) {
$stmt->execute(array(
':subscribercode' => $row['SUBSCRIBER CODE'],
etc...
}
would work.
Using xPath query, I am trying to extract HTML values and put them into an associative array in PHP. I am using a loop to get the rows and cells from the table. But, I can;t figure out how to get the cells in an array embedded within an array that represents the row. Basically, just transferring the table structure to an array. Ideally, it would help to assign keys for the cell data.
I tried combining $key as an array and a counter to assign key/value pair. I and xpath at different points of the structure. I can get fill up the array but I am But I just can't seem to crack it.
$cells = array();
$cell_values = array();
$key = array("MM", "DD", "TIME", "WVHT", "SwH", "SwP", "SwD", "WWH", "WWP", "WWD", "STEEPNESS", "APD");
$i = 3;
while($i <= 5){
$rows = $xpath->query('//table[#class="dataTable"][2]/tr['.$i.']');
if (!is_null($rows)){
foreach ($rows as $row) {
$cells = $row->getElementsByTagName('td');
$i++;
foreach ($cells as $cell) {
$cell_values[] = $cell->nodeValue;
$dataOut[] = array_combine($key, $cell_values);
}
}
}
}
Expected:
Array ( [0] => [1] => [2] => [3] => [4] => [5] => [6] => [7] => [8] => [9]
=> [10] =>
[11] => Array ( [MM] => 02 [DD] => 17 [TIME] => 11:30 am [WVHT]
=> 3.0 [SwH] => 0.3 [SwP] => 10.5 [SwD] => SE [WWH] => 2.6 [WWP] => 8.3
[WWD] => SE [STEEPNESS] => AVERAGE [APD] => 4.4 )
//Next set of row data with $keys
[12] => Array ( [MM] => 02 [DD] => 17 [TIME] => 11:00 am [WVHT] => 3.3 [SwH]
=> 0.3 [SwP] => 10.5 [SwD] => SE [WWH] => 2.6 [WWP] => 8.3 [WWD] => SE
[STEEPNESS] => AVERAGE [APD] => 4.4 )
[13] => Array... etc.
What I Get:
Array ( [0] => [1] => [2] => [3] => [4] => [5] => [6] => [7] => [8] => [9]
=> [10] => [11] => Array ( [MM] => 02 [DD] => 17 [TIME] => 11:30 am [WVHT]
=> 3.0 [SwH] => 0.3 [SwP] => 10.5 [SwD] => SE [WWH] => 2.6 [WWP] => 8.3
[WWD] => SE [STEEPNESS] => AVERAGE [APD] => 4.4 ) [12] => [13] => [14] =>
[15] => [16] => [17] => [18] => [19] => [20] => [21] => [22] => [23] => [24]
=> [25] => [26] => [27] => [28] => [29] => [30] => [31] => [32] => [33] =>
[34] => [35] => )
If you define your keys as values in the $key array rather than keys, you can array_combine that with the values from the <td>s to produce the rows for your result array.
$rows = $xpath->query('//table[#class="dataTable"][2]/tr');
// define these as values so you can use them in array_combine
$key = array("WVHT", "SwH", "SwD", "WWH", "WWP", "WWD", "STEEPNESS", "AMD");
$data = array();
$cells = array();
if (!is_null($rows)) {
foreach ($rows as $row) {
$cells = $row->getElementsByTagName('td');
// get all the cell values from the row
$row_values = [];
foreach ($cells as $cell) {
$row_values[] = $cell->nodeValue;
}
// combine the keys with the values for this row and add the row to $data
$data[] = array_combine($key, $row_values);
}
}
I'm trying to organize my mysql table into a multidimension php tree array.
For example, I'm trying to organize my products in a hierarchy for easy selection to narrow down the result the narrower they go in the result.
I am returned mysql rows like this:
Array
(
[1] => Amazon
[2] => Kindle Fire
[3] =>
[4] =>
[5] =>
[6] =>
[7] =>
[8] =>
[9] => 1
)
Array
(
[1] => Amazon
[2] => Kindle Fire HD
[3] => WiFi
[4] => 7"
[5] =>
[6] => 16GB
[7] =>
[8] =>
[9] => 2
)
Array
(
[1] => Amazon
[2] => Kindle Fire HD
[3] => WiFi
[4] => 7"
[5] =>
[6] => 32GB
[7] =>
[8] =>
[9] => 3
)
Array
(
[1] => Amazon
[2] => Kindle Fire HD
[3] => WiFi
[4] => 8.9"
[5] =>
[6] => 16GB
[7] =>
[8] =>
[9] => 4
)
Array
(
[1] => Amazon
[2] => Kindle Fire HD
[3] => WiFi
[4] => 8.9"
[5] =>
[6] => 32GB
[7] =>
[8] =>
[9] => 5
)
Array
(
[1] => Amazon
[2] => Kindle Fire HD
[3] => 4G LTE
[4] => 8.9"
[5] =>
[6] => 32GB
[7] =>
[8] =>
[9] => 6
)
Array
(
[1] => Amazon
[2] => Kindle Fire HD
[3] => 4G LTE
[4] => 8.9"
[5] =>
[6] => 64GB
[7] =>
[8] =>
[9] => 7
)
Array
(
[1] => Amazon
[2] => Kindle Fire HDX
[3] => Wifi
[4] => 7"
[5] =>
[6] => 16GB
[7] =>
[8] =>
[9] => 8
)
Array
(
[1] => Amazon
[2] => Kindle Fire HDX
[3] => Wifi
[4] => 7"
[5] =>
[6] => 32GB
[7] =>
[8] =>
[9] => 9
)
Array
(
[1] => Amazon
[2] => Kindle Fire HDX
[3] => Wifi
[4] => 7"
[5] =>
[6] => 64GB
[7] =>
[8] =>
[9] => 10
)
...etc
Note the last array value is the Product ID.
And I'm looking for help writing a recursive function that will result in an array that looks like:
Array(
'Amazon' => Array(
'Kindle Fire' => 1,
'Kindle Fire HD' => Array(
'WiFi' => Array(
'7"' => Array(
'16GB' => 2,
'32GB' => 3
)
'8.9"' => Array(
'16GB' => 4,
'32GB' => 5
)
)
)
)
)
I've tried something like:
while($row = mysqli_fetch_row($res)) {
$id = $row[0];
unset($row[0]);
unset($row[count($row)]);
$row[] = $id; // Moves id to last array value
for($i = 1; $i < count($row); $i++) {
if($i == 1) {
if(!array_key_exists($row[$i], $data)) {
// Insert key
$data[$row[$i]] = array();
}
}
else {
$level = $data[$row[$i-1]];
if(array_key_exists($row[$i], $level)) {
// Key exists
}
else {
// Insert key
}
}
}
}
I think your code has a good intention: using $level to hold the current depth. But at the moment this won't work, because you are copying via $level = $data[$row[$i-1]]; - instead you need to refer to it, e.g. with $level =& $data[$row[$i-1]];.
$result = array();
while ($row = mysqli_fetch_row($res)) [
$id = array_shift($row);
if (!isset($maxIterator))
$maxIterator = count($row)-1;
$current =& $result;
for ($i=0; $i<$maxIterator; $i++) {
if (empty($row[$i]))
break;
if (!array_key_exists($row[$i], $current))
$current[ $row[$i] ] = array();
$current =& $current[ $row[$i] ];
}
//for properly ended and wasn't broken out of sooner
if ($i == $maxIterator) {
if (!array_key_exists($row[$i], $current))
$current[ $row[$i] ] = 1;
else
$current[ $row[$i] ]++;
}
}
array_shift basically does, what you needed two lines for: get the first element of an array and then remove it. Then I save the result of the count in a variable, so it doesn't need to be recalculated in every iteration of the for AND while.
Also I would suggest setting $maxIterator manually. With the shown result a good default would be 5. This way all values before the 5th. will be used for nesting and the 5th itself will be used to count (in your example this is storage size).
As the for will execute $i++ after the last iteration (and then it fails the condition and hence the loop breaks), it can be used for the counting.
Personally I would overthink what exactly you are doing and maybe use a specifc structure for that. However, this code should give you a good impression how it can be solved using references.
I have array format like:
Array
(
[Australia] => Array
(
[0] => [1990,0.01],
[1] => [1991,0.02],
[2] => [1992,0.02],
[3] => [1993,0.02],
[4] => [1994,0.02],
[5] => [1995,0.02],
[6] => [1996,0.02],
[7] => [1997,0.02],
[8] => [1998,0.02],
[9] => [1999,0.02],
[10] => [2000,0.02],
[11] => [2001,0.02],
[12] => [2002,0.02],
[13] => [2003,0.02],
[14] => [2004,0.02],
[15] => [2005,0.02],
[16] => [2006,0.02],
[17] => [2007,0.02],
[18] => [2008,0.02],
[19] => [2009,empty],
[20] => [2010,empty],
[21] => [2011,empty],
[22] => [2012,empty],
[23] => [2013,empty],
[24] => [2014,empty],
[25] => [2015,empty]
)
[Pakistan] => Array
(
[0] => [1990,0.00],
[1] => [1991,0.00],
[2] => [1992,0.00],
[3] => [1993,0.00],
[4] => [1994,0.00],
[5] => [1995,0.00],
[6] => [1996,0.00],
[7] => [1997,0.00],
[8] => [1998,0.00],
[9] => [1999,0.00],
[10] => [2000,0.00],
[11] => [2001,0.00],
[12] => [2002,0.00],
[13] => [2003,0.00],
[14] => [2004,0.01],
[15] => [2005,0.01],
[16] => [2006,0.00],
[17] => [2007,0.00],
[18] => [2008,0.00],
[19] => [2009,empty],
[20] => [2010,empty],
[21] => [2011,empty],
[22] => [2012,empty],
[23] => [2013,empty],
[24] => [2014,empty],
[25] => [2015,empty]
)
)
and i want to replace 'empty' with 0 without change the array structure and elements position. I stuck how to do..
You can use array_walk_recursive function:
function replace_empty(&$item, $key) {
$item = str_replace('empty', '0', $item);
}
array_walk_recursive($your_array, 'replace_empty');
You could use the array_walk_recursive function, with a callback function that would replace empty by 0.
For example, considering your array is declared this way :
$myArray[0] = array(23, empty, 43, 12);
$myArray[1] = array(empty, empty, 53, 19);
Note : I supposed you made a typo, and your arrays are not containing only a string, but several sub-elements.
You could use this kind of code :
array_walk_recursive($myArray, 'replacer');
var_dump($myArray);
With the following callback functon :
function replacer(& $item, $key) {
if ($item === empty) {
$item = 0;
}
}
Note that :
the first parameter is passed by reference !
which means modifying it will modify the corresponding value in your array
I'm using the === operator for the comparison
And you'd get the following output :
array(
0 =>
array
0 => int 23
1 => int 0
2 => int 43
3 => int 12
1 =>
array
0 => int 0
1 => int 0
2 => int 53
3 => int 19)
I would foreach in both indices (not tested):
foreach($array as $country){
foreach($country as &$field){
if($field[1] == 'empty'){
$field[1] = 0;
}
}
}
(I assume empty is a string)
EDIT:
If this [1990,0.00] is not an array but a string, you could use str_replace instead
foreach($array as $country){
foreach($country as &$field){
$field = str_replace('empty', '0.00', $field);
}
}
}