PHP Loop with While Loop confusion - php

I currently have a simple WHILE loop running as follows:
while($los = $result->fetch_row())
{
echo"<tr><td>".$los[0]."</td>";
echo"<td>".$los[1]."</td>";
echo"<td>".$los[2]."</td></tr>";
}
The contents of $los is as follows:
London => 15 => 32
Glasgow => 23 => 45
Leeds => 1 => 12
Truro => 5 => 23
All working fine but what I am struggling with is that I have a second array $outs, the contents of which are:
London => 3
Glasgow => 5
Liverpool => 2
Poole => 1
Within the first while loop I am trying to subtract the value for $outs from $los when the location name matches. I have tried adding the following inside the while loop but no joy:
if($los[0] == $outs[0]){
$los[1] = $los[1]-$outs[1];
}
But no joy, also when I have tried print_r($outs) from within the while loop, all it returns is:
Poole => 1
Poole => 1
Poole => 1
Poole => 1
I cannot fathom where I am going wrong or even if this is possible. Is the $outs array being modified as it's within the first loop? Any ideas, suggestion or pointers welcomed on how I might achieve this.
VAR DUMPS
So, as requested the contents of the two arrays are:
$los
London => 15 => 32
Glasgow => 23 => 45
Leeds => 1 => 12
Truro => 5 => 23
$outs
London => 3
Glasgow => 5
Liverpool => 2
Poole => 1
However, when I vardump or print_r for $outs when it is in the while($los = $result->fetch_row()) the contents are:
Poole => 1
Poole => 1
Poole => 1
Poole => 1
FURTHER CODE
The code to obtain the array for $outs is:
$query19 = "SELECT Country, COUNT(Country), Resp FROM `tresults_` WHERE q39 = 'Complete' GROUP BY Country;";
$result19 = $mysqli->query($query19);
while($row19 = $result19->fetch_assoc()){
$outs = $row19;
}

Please consider to post the RAW Content that was produced by var_dump and include a full but minimal script to produce the error.
What is unclear here seem to be if $outs is a (1) Key-Value Array or a if it's (2) containing sub-arrays.
Option 1:
$outs = [
"London" => 3,
"Glasgow" => 5,
"Liverpool" => 2,
"Poole" => 1
];
Option 2:
$outs = [
["London", 3],
["Glasgow", 5],
["Liverpool", 2],
["Poole", 1]
];
I did for testing assume your input rows look like this:
$citys = [
["London", 15, 32],
["Glasgow", 23, 45],
["Leeds", 1, 12],
["Truro", 5, 23]
];
Depending on this you sould adjust the if inside your while loop.
For option 1:
foreach ($citys as $los) {
if (array_key_exists($los[0], $outs)) {
$los[1] = $los[1] - $outs[$los[0]];
}
echo " <tr><td > " . $los[0] . "</td > ";
echo "<td > " . $los[1] . "</td > ";
echo "<td > " . $los[2] . "</td ></tr > ";
}
For option 2 it's a little bit more code, as we need to search for the cityname index inside $outs first. In php > 5.5 it could be done using array_column which would be easier.
foreach ($citys as $los) {
$indexInOuts = null;
foreach($outs as $index => $out){
if($los[0] === $out[0]){
$indexInOuts = $index;
break;
}
}
if($indexInOuts !== null){
$los[1] = $los[1] - $outs[$indexInOuts][1];
}
echo " <tr><td > " . $los[0] . "</td > ";
echo "<td > " . $los[1] . "</td > ";
echo "<td > " . $los[2] . "</td ></tr > ";
}
The output for both options would be like:
London 12 32
Glasgow 18 45
Leeds 1 12
Truro 5 23
And as stated in the comments you are replacing the $outs every time. So edit it to look like this:
$outs = [];
while ($row19 = $result19->fetch_assoc()) {
$outs[] = $row19;
}

Related

multidimensional search not showing all results

I have a multidimensional array search
my array looks like this
Array
(
[0] => Array
(
[id] => 1
[location] => 3
[location_fees] => 3
[gross_percentage] => 25
[transaction_percentage] => 0
[user_name] => admin
[user_id] => 1
[gross] => yes
[transaction] => no
)
[1] => Array
(
[id] => 2
[location] => 5
[location_fees] => 5
[gross_percentage] => 0
[transaction_percentage] => 24
[user_name] => admin
[user_id] => 1
[gross] => no
[transaction] => yes
)
[2] => Array
(
[id] => 3
[location] => 2
[location_fees] => 5
[gross_percentage] => 10
[transaction_percentage] => 0
[user_name] => admin
[user_id] => 1
[gross] => yes
[transaction] => no
)
)
i use the following php, i know it can probably be done cleaner or a lot less code so if you have any ideas how to get the same result i am def all about learning and i am all ears!
so here is the PHP i use:
$key = false;
$search = ['gross' => 'yes'];
foreach ($results as $k => $v) {
if ($v['gross'] == $search['gross'] ) {
$key = $k;
$location_fees = array_search('yes', array_column($results, 'gross','location_fees'));
echo "The location fees: ". $location_fees ." % <br><br>";
$gross_percentage = array_search('yes', array_column($results, 'gross', 'gross_percentage'));
echo "The gross_percentage is: ".$gross_percentage ."% <br><br>";
} else {
$tran_perc = array_search('yes', array_column($results, 'transaction', 'transaction_percentage'));
echo "The locations percentage is: ".$tran_perc ." % <br>";
$the_loc = array_search('yes', array_column($results, 'transaction', 'location'));
echo "The location is: ".$the_loc ." <br>";
$location_fees = array_search('no', array_column($results, 'gross','location_fees'));
echo "The location fees: ". $location_fees ." % <br><br>";
}
}
and my results on the page look like this:
key 0
The location fees: 3 %
The gross_percentage is: 25%
key 1
The locations percentage is: 24 %
The location is: 5
The location fees: %
key 2
The location fees: 8 %
The gross_percentage is: 25%
it refuses to show the locations fee from key #1
NOW the strange parts is, if i change the location fees to say 3, it then shows up. but it will not with the number "5" which is also the location #
Is there a reason this is a conflict with JUST that number "5"? Notice Key "0" has location of "3" and location fees of "3" and it does not cause any issues.
I have been stuck on this for hours, it will work for keys # 0 and #2 without any issues. Any ideas?
The reason you are running into this issue is your call to array_column:
array_column($results, 'gross','location_fees')
this causes the gross values from $results to be re-indexed by the location_fees values, which for your data would result in something like
[3 => 'yes', 5 => 'no', 5 => 'yes']
As you can see, you have two 5 numeric keys, which is not valid, so the second one overwrites the first and you end up with
[3 => 'yes', 5 => 'yes']
and your array_search for no fails, hence you get no results. You will have this problem everywhere you get a replicated value.
I'm not sure why you are taking this approach anyway. It seems you have the numbers you want in $v anyway:
$search = ['gross' => 'yes'];
foreach ($results as $k => $v) {
echo "key $k<br>" . PHP_EOL;
if ($v['gross'] == $search['gross'] ) {
$location_fees = $v['location_fees'];
echo "The location fees: ". $location_fees ." % <br><br>" . PHP_EOL;
$gross_percentage = $v['gross_percentage'];
echo "The gross_percentage is: ".$gross_percentage ."% <br><br>" . PHP_EOL;
} else {
$tran_perc = $v['transaction_percentage'];
echo "The locations percentage is: ".$tran_perc ." % <br>" . PHP_EOL;
$the_loc = $v['location'];
echo "The location is: ".$the_loc ." <br>" . PHP_EOL;
$location_fees = $v['location_fees'];
echo "The location fees: ". $location_fees ." % <br><br>" . PHP_EOL;
}
}
Output:
key 0<br>
The location fees: 3 % <br><br>
The gross_percentage is: 25% <br><br>
key 1<br>
The locations percentage is: 24 % <br>
The location is: 5 <br>
The location fees: 5 % <br><br>
key 2<br>
The location fees: 5 % <br><br>
The gross_percentage is: 10% <br><br>
Demo on 3v4l.org

Sum of all values on key with different arrays

Below are five arrays. The idea is to count all the values for matching keys. And keep the single appearances.
All these should appear in a new array. So, 14855 should have value 6, and 101 value 7 etc.
$arr_one = Array ( [14638] => 5 [14855] => 5 )
$arr_two = Array ( [101] => 4 [10141] => 4 [1015] => 4 [1020] => 4 [10353] => 4 [1048] => 4 [10582] => 4 [1060] => 4 [10675] => 4 [1068] => 4 [1084] => 4 [1098] => 4
$arr_three = Array ( [101] => 3 [10141] => 3 [602] => 3 [341] => 3 [3523] => 3 [922] => 3 [2099] => 3 [7305] => 3 [222] => 3 [537] => 3 [2792] => 3
$arr_four = Array ( [10141] => 2 [1232] => 2 [10909] => 2 [129] => 2 [155] => 2 [] => 2 [156] => 2
$arr_five = Array ( [14855] => 1 [96] => 1 [120] => 1 [129] => 1 [155] => 1 [156] => 1
Is there a way to do this, and with the option that you can add more arrays later as well?
Hope anyone can help me with this brainteaser for me!
This was a challenged question, but at the same time a nasty one ;)
I enjoyed 3 hours works and it is done.
First of all to say your array in the question is not well formed.
This question can be for sure solved in many ways. This is an example of one approach to achieve the goal and demonstrate how to do it, so you are welcome to play with it and learn more.
I wrote some notes inside the code. You can expand this to handle unlimited arrays, but the sum calculation is only for 2 keys, if you have more then 2 keys, I will leave to you, as now you have the concept.
<?php
$arr1 = [14638 => 5, 14855 => 5];
$arr2 = [101 => 4, 10141 => 4, 1015 => 4, 1020 => 4, 10353 => 4, 1048 => 4, 10582 => 4, 1060 => 4, 10675 => 4, 1068 => 4, 1084 => 4, 1098 => 4];
$arr3 = [101 => 3, 10141 => 3, 602 => 3, 341 => 3, 3523 => 3, 922 => 3, 2099 => 3, 7305 => 3, 222 => 3, 537 => 3, 2792 => 3];
$arr4 = [10141 => 2, 1232 => 2, 10909 => 2, 129 => 2, 155 => 2, 0 => 2, 156 => 2];
$arr5 = [14855 => 1, 96 => 1, 120 => 1, 129 => 1, 155 => 1, 156 => 1];
//We merge arrays
$arrMerge = array($arr1, $arr2, $arr3, $arr4, $arr5);
//Count how many keys in merged array subtract 1 for out for loop
$arrCount = count($arrMerge) - 1;
//Our new array that contain a copy of all keys and values with out doubles
$arrNew = array();
//Creating new array of all arrays
for ($i = 0; $i < $arrCount; $i ++)
{
foreach ($arrMerge[$i] as $key => $value)
{
//echo "Key: $key; Value: $value<br />\n";
$arrNew[$key] = $value;
}
}
//The algorithm
for ($i = 0; $i < $arrCount; $i ++)
{
echo "<b>Array " . $i . " comparing with : </b>";
for ($j = $arrCount; $j > $i; $j --)
{
echo "<br> Array " . $j . " : <br/>";
for ($k = 0; $k < count($arrMerge[$i]); $k ++)
{
$key1 = array_keys($arrMerge[$i]);
$value1 = array_values($arrMerge[$i]);
for ($l = 0; $l < count($arrMerge[$j]); $l ++)
{
$key2 = array_keys($arrMerge[$j]);
$value2 = array_values($arrMerge[$j]);
if ($key1[$k] == $key2[$l])
{
echo "match found: " . $key1[$k] . " and " . $key2[$l] . " are identical keys, ";
echo "we sum : " . $value1[$k] . " and " . $value2[$l] . "<br />";
//We update the new array with the summed values.
$arrNew[$key1[$k]] = $value2[$l] + $value1[$k];
}
}
}
}
echo "<br><br>";
}
// printing results
echo "<b>This our new array with sum values</b><br/>";
foreach ($arrNew as $key => $value)
{
echo "Key: $key; Value: $value<br />\n";
}
?>
It is tested and here is the output of this code, The first part is a list of matching keys and last part as you can see the key 14855 got value 6 and key 101 got value 7 etc.:
Comparing all 5 Arrays Keys output
Array 0 comparing with :
Array 4 :
match found: 14855 and 14855 are identical keys, we sum : 5 and 1
Array 3 :
Array 2 :
Array 1 :
Array 1 comparing with :
Array 4 :
Array 3 :
match found: 10141 and 10141 are identical keys, we sum : 4 and 2
Array 2 :
match found: 101 and 101 are identical keys, we sum : 4 and 3
match found: 10141 and 10141 are identical keys, we sum : 4 and 3
Array 2 comparing with :
Array 4 :
Array 3 :
match found: 10141 and 10141 are identical keys, we sum : 3 and 2
Array 3 comparing with :
Array 4 :
match found: 129 and 129 are identical keys, we sum : 2 and 1
match found: 155 and 155 are identical keys, we sum : 2 and 1
match found: 156 and 156 are identical keys, we sum : 2 and 1
Last part our new Array with sum of each Key
This our new array with sum values
Key: 14638; Value: 5
Key: 14855; Value: 6
Key: 101; Value: 7
Key: 10141; Value: 5
Key: 1015; Value: 4
Key: 1020; Value: 4
Key: 10353; Value: 4
Key: 1048; Value: 4
Key: 10582; Value: 4
Key: 1060; Value: 4
Key: 10675; Value: 4
Key: 1068; Value: 4
Key: 1084; Value: 4
Key: 1098; Value: 4
Key: 602; Value: 3
Key: 341; Value: 3
Key: 3523; Value: 3
Key: 922; Value: 3
Key: 2099; Value: 3
Key: 7305; Value: 3
Key: 222; Value: 3
Key: 537; Value: 3
Key: 2792; Value: 3
Key: 1232; Value: 2
Key: 10909; Value: 2
Key: 129; Value: 3
Key: 155; Value: 3
Key: 0; Value: 2
Key: 156; Value: 3

Add value in specific index array

i have array data like this.
[0] => Array (
[id] => 1
[id_requestor] => 1
[jam_input] => 2015-06-20 06:00:00
[jam_pakai] => 2015-06-28 08:00:00
[total_poin] => 30
)
[1] => Array (
[id] => 2
[id_requestor] => 2
[jam_input] => 2015-06-20 07:00:00
[jam_pakai] => 2015-06-28 08:00:00
[total_poin] => 10
)
[2] => Array (
[id] => 3
[id_requestor] => 3
[jam_input] => 2015-06-20 06:30:00
[jam_pakai] => 2015-06-28 08:00:00
[total_poin] => 5
)
In above data, there is total_poin. This total_poin that i use later.
I want to sort total_poin array descending.
But i wont to use php built in array function.
Cause i have to use method from research paper like this.
for i=0 to i<main queue.size
if jobi+1 length > jobi length then
add jobi+1 in front of job i in the queue
end if
if main queue.size = 0 then
add job i last in the main queue
end if
And here is my implementation :
function LJFAlgorithm($time_str) {
$batchData = getBatch($time_str);
$ljf = [];
for ($i=0; $i < count($batchData)-1; $i++) {
echo $batchData[$i+1]['total_poin'] ." >= ". $batchData[$i]['total_poin'] . " = " . ($batchData[$i+1]['total_poin'] >= $batchData[$i]['total_poin']);
if ($batchData[$i+1]['total_poin'] >= $batchData[$i]['total_poin']) {
echo ", Add " . $batchData[$i+1]['total_poin'] . " in front of " . $batchData[$i]['total_poin'];
} else {
echo ", Add " . $batchData[$i]['total_poin'] . " in front of " . $batchData[$i+1]['total_poin'];
}
echo '<br/>';
}
print_r($ljf);
}
But it not work perfectly, i get one data missing.
Here is my output code :
10 >= 30 = , Add 30 in front of 10
5 >= 10 = , Add 10 in front of 5
5 value not added in array.
How to fix that?
Thank you very much.
Try this
for ($i=0; $i <= count($batchData)-1; $i++)

PHP if() not working as designed? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This is a little bit confusing on why this won't work. I can do a work around, but any ideas? It's to match an uploaded CSV to a configuration in a database. Returns only the first 5 columns. The rest, user specified ones (should print Echo) do not show up.
$csv_col while looping =
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
$getConfiguration[0] =
Array
(
[config_key] => 22
[config_client_ident] => 105
[config_s_timestamp] => 1378008000
[config_e_timestamp] =>
[config_kpi_1] => 81
[config_kpi_2] => 82
[config_kpi_3] => 83
[config_kpi_4] => 84
[config_kpi_5] =>
[config_kpi_6] =>
[config_kpi_7] =>
[config_kpi_8] =>
[config_kpi_9] =>
[config_kpi_10] =>
[config_kpi_11] =>
[config_kpi_12] =>
[config_kpi_13] =>
[config_kpi_14] =>
[config_kpi_15] =>
[config_kpi_16] =>
[config_kpi_17] =>
[config_kpi_18] =>
[config_kpi_19] =>
[config_kpi_20] =>
[config_kpi_21] =>
[config_kpi_22] =>
[config_kpi_23] =>
[config_kpi_24] =>
[config_kpi_25] =>
[config_kpi_26] =>
[config_kpi_27] =>
[config_kpi_28] =>
[config_kpi_29] =>
[config_kpi_30] =>
[config_kpi_31] =>
[config_kpi_32] =>
[config_kpi_33] =>
[config_kpi_34] =>
[config_kpi_35] =>
[config_kpi_36] =>
[config_kpi_37] =>
[config_kpi_38] =>
[config_kpi_39] =>
[config_kpi_40] =>
[config_kpi_41] =>
[config_kpi_42] =>
[config_kpi_43] =>
[config_kpi_44] =>
[config_kpi_45] =>
[config_kpi_46] =>
[config_kpi_47] =>
[config_kpi_48] =>
[config_kpi_49] =>
[config_kpi_50] =>
)
$csvRead[0]
Array
(
[0] => Data Date
[1] => Agent IDENT
[2] => Client IDENT
[3] => Location IDENT
[4] => Program IDENT
[5] => xx VSAT
[6] => xx SWSAT
[7] => xx NSODS
[8] => xx SWDSAT
)
Returned from query
Array
(
[0] => Array
(
[key_id] => 84
[key_enabled] => 1
[key_name] => xx SWDSAT
[key_desc] => xx CSAT Somewhat Dissatisfied
)
)
// Build the check arary
$checkArray = array("Data Date", "Agent IDENT", "Client IDENT", "Location IDENT", "Program IDENT");
$fileVerification = true;
$config_col = 1;
// Loop through the 50 available columns
while($config_col <= 50){
$csv_col = $config_col - 1;
print $csv_col . " ";
// Make sure something is in those columns
if($getConfiguration[0]['config_kpi_'.$config_col] != ''){
// There is, now lets query and get those names.
$getNamesQuery[] = "SELECT * FROM kpi_keys WHERE key_id=".$getConfiguration[0]['config_kpi_'.$config_col];
$getNamesResult = dbInsert($getNamesQuery);
// Compare the first 5 columns
if($csv_col < 5){
if($csvRead[0][$csv_col] == $checkArray[$csv_col]){
$output .= '<div class="messageGood"> - '.$csvRead[0][$csv_col].' column verified.</div>';
} else {
$output .= '<div class="messageBad"> - Column "'.$csvRead[0][$csv_col].'" did not match "'.$checkArray[$csv_col].'" in the current configuration.</div>';
$fileVerification = false;
}
} else {
// Now lets compare the customizable columns. We're going to do names and ID's to make sure.
print "Echo";
}
$getNamesQuery = null;
}
$config_col++;
}
// Now we check the information
print "<pre>";
print_r($getConfiguration[0]);
print_r($csvRead[0]);
print_r($getNamesResult);
print "</pre>";
Answer (Thanks Wrikken)
// Loop through the 50 available columns
while($config_col <= 50){
$csv_col = $config_col - 1;
$partOne = '';
$partTwo = '';
// Make sure something is in those columns
// Compare the first 5 columns
if($csv_col < 5){
if($csvRead[0][$csv_col] == $checkArray[$csv_col]){
$partOne .= '<div class="messageGood"> - '.$csvRead[0][$csv_col].' column verified.</div>';
} else {
$partOne .= '<div class="messageBad"> - Column "'.$csvRead[0][$csv_col].'" did not match "'.$checkArray[$csv_col].'" in the current configuration.</div>';
$fileVerification = false;
}
}
if($getConfiguration[0]['config_kpi_'.$config_col] != ''){
print $csv_col . " ";
// There is, now lets query and get those names.
$getNamesQuery[] = "SELECT * FROM kpi_keys WHERE key_id=".$getConfiguration[0]['config_kpi_'.$config_col];
$getNamesResult = dbInsert($getNamesQuery);
// Now lets compare the customizable columns. We're going to do names and ID's to make sure.
$partTwo = "Comparison";
$getNamesQuery = null;
}
$config_col++;
}
$output .= $partOne . $partTwo;
while($csv_col < 5){
if($csvRead[0][$csv_col] == $checkArray[$csv_col]){
$output .= '<div class="messageGood"> - '.$csvRead[0][$csv_col].' column verified.</div>';
if only runs one time,if you want to concatenate use while, it will run..until the end.

extract information from an array

Is there any way to transform an array looking like this:
Array ( [level-1] => 2 [quarter-1] => 1 [year-1] => 2014 [level-2] => 2 [quarter-2] => 2 [year-2] => 2015 [level-49] => 2 [quarter-49] => 2 [year-49] => 2015 [level-58] => 1 [quarter-58] => 1 [year-58]
and take only the numbers after the keywords to use them in an sql table. For example, the table would look like:
ID 1 Level 2 Quarter 1 Year 2014
ID 2 level 2 quater 2 Year 2015
ID 49 level 2 quarter 2 year 2015
Etc
I tried
if(!empty($_POST)){
print_r ($_POST);
echo "<br/><br/>";
$s=$_POST;
echo $abc= implode(',', $s);
for($a=0;$a<count($s);$a++){
$ar=explode(',',$abc);
echo $var=$ar[$a];
}
}
But the result i get is something like :
2,1,2014,2,2,2015,2,2,2015...
I need also the ID to be shown. But i most importantly do not know how to interpret the results to put them in the db..
Try this :
$array = array ( "level-1" => 2, "quarter-1" => 1, "year-1" => 2014, "level-2" => 2, "quarter-2" => 2, "year-2" => 2015, "level-49" => 2, "quarter-49" => 2, "year-49" => 2015, "level-58" => 1, "quarter-58" => 1, "year-58"=>2016);
foreach(array_chunk($array,3,true) as $val){
foreach($val as $k=>$v){
if(strpos($k, "level") !== false){
$temp = explode("-",$k);
$id = $temp[1];
$level = $v;
}
if(strpos($k, "quarter") !== false){
$quarter = $v;
}
if(strpos($k, "year") !== false){
$year = $v;
}
}
echo "ID ".$id." Level ".$level." Quarter ".$quarter." Year ".$year;
echo "<br>";
}
Output :
ID 1 Level 2 Quarter 1 Year 2014
ID 2 Level 2 Quarter 2 Year 2015
ID 49 Level 2 Quarter 2 Year 2015
ID 58 Level 1 Quarter 1 Year 2016
I don't know to code in PHP, so i will explain you the logic for doing it.
for(int i=0;i<array.length;i=i+3)
{
//get value from array[i]; get the level-x field and retrieve the x value, then extract integers accordingly from it after keywords. In java StringTokenizer can be used for this, or regex etc
//again get value from array[i+1] and extract the integer
//get the value from array[i+2] and do the same as above.
}
If the array is shuffled, you can match it with the level-x to get the exact tuple to insert. So level-x, the x value acts as an index that groups all related value.

Categories