There is some logic error in my code and I am not sure what I am doing wrong here.
Setting up things first, I have a .json file that I am reading which is in this layout:
So the polygon element is at every 1, 3, 5, .. and the school name is one prior to that.
Now I have another .csv file from where I am taking different lat and long values. Basically I have to see if that lat long from the csv file is inside any of these polygons as described in the json file.
Here is my part of the PHP code that takes in the json file and csv file. My logic is that, I take one lat and long value from the CSV and then want to go over each polygon in the json file.
If you follow the code below, I take in the values and when I meet the condition that it is outside a polygon, it just breaks out of the second while loop, takes another set of lat and longs.
$string = file_get_contents("Schools.json", 0, null, null);
$json_a = json_decode($string, true);
$start_row = 4;
$rowID = 1;
$polygonIndex = 1;
$insideCheck = 0;
$file = fopen("ActiveProperty.csv", "r");
while (($row = fgetcsv($file)) !== FALSE){
if($rowID >= $start_row){
$points = array($row[52] . ' ' . $row[49]);
$polygonIndex = 1;
while ($polygonIndex < 454){
$polygon = $json_a[$polygonIndex]['Polygons'];
foreach($points as $key => $point) {
if ($pointLocation->pointInPolygon($point, $polygon) == "outside"){
echo "point " . ($key+1) . " ($point): " . $pointLocation->pointInPolygon($point, $polygon);
echo "<br>";
$polygonIndex = $polygonIndex + 2;
echo $polygonIndex;
$insideCheck = 0;
break;
}
else {
echo $json_a[$polygonIndex - 1];
echo "<br>";
echo "point " . ($key+1) . " ($point): " . $pointLocation->pointInPolygon($point, $polygon);
echo "<br>";
$insideCheck = 1;
break;
}
}
if ($insideCheck = 0) {
echo "out of foreach 0";
continue;
}
else {
echo "out of foreach";
$insideCheck = 0;
break;
}
}
}
$rowID++;
}
Here is a sample output that I have:
Lat and longs in this image is from the csv file.
The expected output should be that with that lat and long, it should go over the polygons in the json and if its inside, return the first element which is the school. Here $polygonIndex just stays 3 which I am guessing is the issue.
If this is still unclear what I am trying to do, please let me know. Thanks.
Related
Want to create a php variable using text before and after the value of another variable.
variable variables. But have only seen examples of assignment with no text.
$vsBOA_W[]=$rows['vsBOA_W'];
// BOA = team 3-char abbreviation. Looking for something similar to above but insert 3-char abbreviations based on a input file.
$numOfTeams = 3; // Determined from external source
$teamAbbr = array("BOA","CAA","CHN"); // For simplicity for this example. This array would normally be created from an external source.
for($i=0; $i<$numOfTeams; $i++) { // I know I can use size of array instead of nunOfTeams. That's not the issue.
echo $teamAbbr[$i]."<br>"; // for testing
$$("vs".{'$teamAbbr[$i]'}."_W[]"} = $rows['$$("vs".{'$teamAbbr[$i]'}."_W"}']; // a total guess
}
I expect the end result to look like:
$vsBOA_W[]=$rows['vsBOA_W'];
for BOA
Update #2: I tried the following (breaking down each step) and get the same error on $$TeamWins assignment.
for($i=0; $i<$numOfTeams; $i++) {
echo $teamAbbr[$i]."<br>";
$TeamWins = 'vs' . $teamAbbr[$i] . '_W';
echo "TeamWins=$TeamWins<br>";
$TeamWinsHold = $rows[$TeamWins];
echo "TeamWinsHold=$TeamWinsHold<br>";
$$TeamWins[] = $TeamWinsHold;
}
Update #3:
for($i=0; $i<$numOfTeams; $i++) {
echo $teamAbbr[$i]."<br>";
$TeamWins = 'vs' . $teamAbbr[$i] . '_W';
echo "TeamWins=$TeamWins<br>";
$TeamWinsHold = $rows[$TeamWins];
echo "TeamWinsHold=$TeamWinsHold<br>";
${$TeamWins}[] = $TeamWinsHold;
}
foreach(${$TeamWins} as $value) {
echo "value=$value<br>"; // only displays last element or value assigned from above loop.
}
Update #4 (final):
$teamW = array();
$teamL = array();
for($i=0; $i<$numOfTeams; $i++) {
//echo $teamAbbr[$i]."<br>";
$teamWName = 'vs' . $teamAbbr[$i] . '_W';
$teamLName = 'vs' . $teamAbbr[$i] . '_L';
//echo "teamWName=$teamWName<br>";
//echo "teamLName=$teamLName<br>";
$teamW[$teamWName] = $rows[$teamWName];
$teamL[$teamLName] = $rows[$teamLName];
}
I don't quite understand the interplay with the rows in your example. But going by your guess assignment, you can always simplify, by forming the variable name upfront:
<?php
$rows = ['xFOOy'=>[], 'xBARy'=>[], 'xBAZy'=>[]];
$items = ['FOO', 'BAR', 'BAZ'];
foreach($items as $abbr)
{
$name = 'x' . $abbr . 'y';
${$name}[] = $rows[$name];
}
But, I'd say you'd be better off with a keyed array than variable variables, as it makes for easier inspection, and there is less chance of namespace clashes.
Now a very kind StackOverflow use has helped me out with a lot of my issues however there's two remaining probelms with my code before it's ready to go, any ideas would be great as i'm currently screaming at it:
First of all i'm using the following to try and pull data from a MySQL Database, return it as a Numeric Array and Order It By ID. There's 2 items in there and no matter what I do I can only get 1 to display (I need it to display ALL data when the table fills up more):
$query = "SELECT * FROM batch ORDER by ID";
$result = $mysqli->query($query);
/* numeric array */
$row = $result->fetch_array(MYSQLI_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);
?>
Secondly, slightly off topic but this code below was given by a StackOverflow user however I can't get it to work, they've geared it to OOP which is not an area i'm familiar with and no matter what I do to correct the $this-> or public / private it still refuses to work (the aim of the code is to have a number in $userinput which gets checked against the $widgetBatches array for the closest match (i.e. input is 1100 and closest is 1000) this then gets deducted from the input (to leave 100) and the process loops again to check and this time returns 100 as the closest, this process continues until the $userinput reaches 0 or a negative number:
<?php
$userinput = 10000; // Our magic variable - user input
$iterations = 0;
function Widget($userinput)
{
$this->iterations++;
$widgetRequested = $userinput;
$widgetBatches = array("250", "500", "1000", "2000");
echo "Iteration " . $iterations;
echo "<br/>";
echo "Widget requested: " . $widgetRequested;
echo "<br/>";
$closest = GetClosest($widgetBatches, $widgetRequested);
echo "Closest: " . $closest;
echo "<br/>";
$widgetRemaining = $widgetRequested - $closest;
echo "Remainder: " . $widgetRemaining;
echo "<hr/>";
if($widgetRemaining > 0)
{
Widget($widgetRemaining);
}
else
{
echo "The value is now below or equaling zero: " . $widgetRemaining . "!";
}
}
function GetClosest($array, $value)
{
$lowest = null;
foreach($array as $val)
{
if($lowest == null || abs($value - $lowest) > abs($val - $value))
{
$lowest = $val;
}
}
return $lowest;
}
?>
This:
<?php
function Widget($input) {
$currentValue = $input; // Set internal variable from input (Think of this as an initial "remainder")
$i = 0;
$widgetBatches = [250, 500, 1000, 2000]; // Setup batch array
while ($currentValue > 0) { // While the remainder is more than 0
$i++;
echo "Iteration " . $i . "<br/>";
echo "Widget requested: " . $currentValue . "<br/>";
$closest = GetClosest($widgetBatches, $currentValue); // Find the closest value from batch array
echo "Closest: " . $closest . "<br/>";
$currentValue = $currentValue - $closest; // Work out new remainder
echo "Remainder: " . $currentValue . "<hr/>";
}
// Loop will exit when remainder is less than 0
echo "The value is now below or equaling zero: " . $currentValue . "!";
}
function GetClosest($array, $value) {
$result = null; // Innitialise the returned variable in case of failure
foreach($array as $val) { // For every array value, unless stopped
$result = $val; // Set result to current array value
if($value <= $result) break; // Stop foreach loop if value is less than or equal to result
}
return $result; // Return last result from Foreach loop
}
Widget(9000);
?>
Hopefully the comments are useful... I put more detail in than I would usually...
Did you try fetchAll(), I use PDO so not sure, but would suggest you use a while loop, like:
while ($result = $mysqli->query($query));
Or:
foreach($result as $r) then $r['data'];
I'm %100 sure the loop will iterate and pull out every data, which you can send to a table or a list.
I wrote query in php file ,my query is:
$query = "SELECT cc.NAME complex_check_name,f.name server_name,
sgk.NAME single_check_name,cc.operator
FROM complex_check cc,
lnksinglechecktocomplexcheck lk,
single_checks sgk,
functionalci f ,
lnkconfigurationitemtosinglecheck lkcg
WHERE cc.id = lk.complex_check_id AND
sgk.id = lk.single_check_id and
sgk.id = lkcg.single_check_id AND
lkcg.config_item_id = f.id ";
if ($result=mysqli_query($link,$query))
{
while ($obj=mysqli_fetch_object($result))
{
$list= $obj->complex_check_name .
"#".
$obj->server_name .
";".
$obj->single_check_name .
$obj-> operator;
echo $list .'<br>';
}
}
The result is :
test_com_check_sep01#INFRASEP01;cpu check sep01&
test_com_check_sep01#INFRASEP01;DB check sep01&
test_com_check_sep01#INFRASEP01;disk space check sep01&
test_com_check_sep02#INFRASEP02;cpu check sep02||
test_com_check_sep02#INFRASEP02;db check sep02||
test_com_check_sep02#INFRASEP02;disk space check sep02||
How can I concatenate the string as:
"test_com_check_sep01=INFRASEP01;cpu check sep01&INFRASEP01;DBcheck sep01&INFRASEP01;disk space check sep01"
"test_com_check_sep02=INFRASEP02;cpu check sep02||INFRASEP02;db check sep02||INFRASEP02;disk space check sep02"
You could store the values into an array and implode afterwards.
$check = array();
if($result = mysqli_query($link,$query)) {
while($obj = mysqli_fetch_object($result)) {
// If value is not stored in check array proceed
if(!in_array($obj->complex_check_name,$check))
$list[$obj->complex_check_name][] = $obj->complex_check_name."=";
$list[$obj->complex_check_name][] = $obj->server_name.";".$obj->single_check_name.$obj->operator;
// Store in check array
$check[] = $obj->complex_check_name;
}
// Loop through stored rows and implode with break
foreach($list as $array) {
echo implode("<br />",$array);
}
}
try this
$concat1 = '';
$concat2 = '';
if ($result=mysqli_query($link,$query))
{
while ($obj=mysqli_fetch_object($result))
{
if($obj->server_name == 'INFRASEP01'){
concat1 .= $obj->complex_check_name . "#".$obj->server_name .";". $obj->single_check_name . $obj-> operator;
}else{
concat2 .= $obj->complex_check_name . "#".$obj->server_name .";". $obj->single_check_name . $obj-> operator;
}
}
}
echo $concat1 .'<br>'.$concat2;
Assuming you want to keep the lines separate for use, you could do this
$list = array("INFRASEP01", "INFRASEP01", "INFRASEP02");
$concatINFRASEP01 = "";
$concatINFRASEP02 = "";
for($lineCounter = 0; $lineCounter < sizeof($list); $lineCounter++)
if(strpos($list[$lineCounter], "INFRASEP01") !== false){
//Found it
$concatINFRASEP01 .= " " . $list[$lineCounter];
}
else if(strpos($list[$lineCounter], "INFRASEP02") !== false){
$concatINFRASEP02 .= " " . $list[$lineCounter];
}
NOTE: I did not test this code so there may be errors.
If you do not need the $list array, then you can do as #Malakiof suggested.
EDIT (01/22/2015): I have improved my answer but left the old one there in case I misunderstood.
//In your case the rows come from the $obj (which most would call $row)
$listOfRows = array("test_com_check_sep01#INFRASEP01;cpu check sep01&","test_com_check_sep01#INFRASEP01;DB check sep01&", "test_com_check_sep02#INFRASEP02;cpu check sep02||");
//Create this array as you go through each row by adding the server_name
//to this array. You can skip making this array and simply make the
//unique array by checking if the array contains the server_name.
$listServerNames = array("INFRASEP01","INFRASEP02","INFRASEP01", "INFRASEP02", "INFRASEP01");
//Only have unique server names to avoid duplicates
$listUniqueServerNames = array_unique($listServerNames);
//this will be your list of concatenated strings
$concatByServerName = array();
//Go through the unique server names one by one
foreach($listUniqueServerNames as $serverName)
//While looking at each unique server name, look through the rows
foreach($listOfRows as $line)
if(strpos($line, $serverName) !== false){
//Found it
if(array_key_exists($serverName, $concatByServerName))
$concatByServerName[$serverName] .= " " . $line;
else
$concatByServerName[$serverName] = $line;
}
If the $listOfRows is very large, consider making a copy of $listOfRows and removing the lines from $listOfRows when you add them to $concatByServerName.
Although this is not the best way to do it, I am trying to keep it simple in order for you to be able to get it to work, while fully understanding what is happening. You can easily improve on this code by looking at your project and streamlining these tasks.
I'm working on a php script that adds up points from voting using the borda count. I've got files read, data set up, but I'm struggling to set up a way to put an individuals points into their array. Right now I have an array of candidates, and an array of votes. I'm attempting to add up the votes and put them inside of the candidate array. The first number in each vote index responds to the first candidate, and so on. I have the program calculating the vote points correctly, but I can't get them to add together so I have the final number once it finishes.
edit: This script is also supposed to be scalable, meaning if I have 6 candidates, rather than 4, it will work. If there's something that jumps out at the reader saying it won't work, please let me know
<?php
$file = $argv[1];
$inputFile = fopen($file,"r");
$candidates = fgets($inputFile);
$candidates = str_replace(' ','',$candidates);
echo $candidates;
$candidates = explode(',',$candidates);
print_r($candidates);
$numCandidates = count($candidates);
echo "The number of candidates is: " . $numCandidates. "\n";
/**
$testFile = file_get_contents("$argv[1]");
$testFile = explode('\n',$testFile);
print_r($testFile);
*/
while (!feof($inputFile)){
$votes[] = trim(fgets($inputFile),"\n");
}
unset($votes[count($votes)-1]);
//$votes = trim("\n",$votes);
//$votes = explode(',',$votes);
print_r($votes);
for ($i = 0; $i<count($votes); $i++){
$votes[$i] = str_replace(',','',$votes[$i]);
}
print_r($votes);
/**
for($x = 0;$x<count($candidates);$x++){
$z = 0;
for($y = 0;$y<count($votes);$y++){
$candidates[$x][$y] = $votes[$y][$z];
}
print_r($candidates[0]);
$z++;
}
*/
for ($x = 0; $x<count($votes);$x++){
global $candidates;
for ($y=0; $y<count($candidates);$y++){
$candidates[$y][0]= (($numCandidates + 1)-$votes[$x][$y]);
echo "\nThe value of candidate $y is " . $candidates[$y][0];
}
}
?>
This is where I'm attempting to add to the amount, but it just keeps overwriting.
for ($x = 0; $x<count($votes);$x++){
global $candidates;
for ($y=0; $y<count($candidates);$y++){
$candidates[$y][0]= (($numCandidates + 1)-$votes[$x][$y]);
echo "\nThe value of candidate $y is " . $candidates[$y][0];
}
}
Edit: When I attempt to use += rather than = in
$candidates[$y][0] = (($numCandidates + 1)-$votes[$x][$y]);
I get an error saying "can't use assign-op operators with overloaded objects nor string offsets"
$candidates[$y][0] = (($numCandidates + 1)-$votes[$x][$y]);
That = should be += so that your loop keeps adding the value, instead of overwriting the existing value on every iteration.
$candidates[$y][0] += (($numCandidates + 1)-$votes[$x][$y]);
I had a script called CSVimporter V3 for PHP that I used to run on a website and it worked fine. A couple of years later I've now dug out the same script to use on another project, all works okay except the CSV files are being read as one long line, as opposed to header row and multiple lines.
Here is part of the script.
Any ideas why it would be being read as a long line?
<?php
// Reference session variable for short-hand
$f = &$_SESSION['csv_file'];
// Open file - fp = file pointer
if (!$fp = #fopen($f, 'r')) {
error(L_ERROR_PREVIEW_NO_FILE);
} else {
// Array to store each row to be inserted
$batch = array();
// Row counter
$rc = 0;
// Work out starting row
switch ($_SESSION['csv_first_row']) {
case 'data':
$start_row = 0;
break;
default:
$start_row = 1;
}
// Get contents, while below preview limit and there's data to be read
while ($data = fgetcsv($fp, 1024, delimiter_to_char($_SESSION['csv_delimiter']))) {
if ($rc < $start_row) {
// Incremement counter
$rc++;
// Go to next loop
continue;
} else {
// Array to store data to be inputted
$values = array();
// Loop data
for ($i = 0; $i < count($data); $i++) {
// If data is wanted, put data into array
if (array_key_exists($i, $column_index)) {
$values[$column_index[$i]] = $data[$i];
}
}
// Sort array into correct order by index
ksort($values);
// Join values together and store in array
$batch[] = '("' . implode('", "', str_replace('"', '\"', $values)) . '","'.$accti.'","'.$impt.'")';
}
}
}
// Close the file
fclose($fp);
I added this at the top of the code and it all works now!
ini_set('auto_detect_line_endings', true);