The code below is more or less a chunk of my code. The $servername and $monthlyincome variables are not actually static as shown here but I changed them so I could add less code here.
If I run this code...
$servername="Server1";
$months = array('January','February','March','April','May','June','July','August','September','October','November','December');
for ($i=0;$i<=24;$i++) {
$new_time = mktime(0,0,0,date("m")+$i,1,date("Y"));
$months_array[date("Y",$new_time)][date("m",$new_time)] = "x";
}
$overallincome = 0;
foreach ($months_array AS $year=>$month) {
foreach ($month AS $mon=>$x) {
$monthlyincome = 3;
$overallincome += $monthlyincome;
$$servername[$months[$mon-1]." ".$year]['monthlyincome']=$monthlyincome;
$$servername[$months[$mon-1]." ".$year]['overallincome']=$overallincome;
}
}
I get this error...
Cannot use string offset as an array in on line 123
Line 123 is this line... $$servername[$months[$mon-1]." ".$year]['monthlyincome']=$monthlyincome;
I can't figure out what I am doing wrong. I have checked other posts on SO with the same error but nothing made sense to me.
Putting it as an answer, then!
$$servername[] seems to be the problem. It's interpreting it as ${$servername[]} where you want it to interpret as ${$servername}[].
Try putting those curly-brackets in there and see if that helps.
Related
Some of my code is throwing error some times, and can't find why.
The error is strpos(): Offset not contained in string on the while statement.
I know what this error means, but I don't know why sometimes I have this error...
Here is the part of code:
if(!empty($args['name'])){
$p = 0;
while(($p = strpos($args['name'],'&',$p)) !== false){
if(substr($args['name'],$p,5) == '&'){
$p += 5;
}else{
++$p;
$args['name'] = substr($args['name'],0,$p).'amp;'.substr($args['name'],$p);
$p += 4;
}
}
}
I tried to change the While statement by:
while(strlen($args['name']) >= $p && ($p = strpos($args['name'],'&',$p)) !== false){
But it doesn't fix the issue.
By the way, this code comes from a wordpress plugin, here is the doc:
/** A workaround for seems to be an overlook in WordPress core.
* Dealing with '&' in term name.
* A term name containing '&' is stored in database with '&' instead of '&',
* but search in get_terms is done on raw '&' coming from $_POST variable.
*/
Do you have any ideas? Why this code is sometimes wrong?
Thank you
FIXED
My variable was an Array ...
This code should work fine. Is ok.
In your case $p can't be greater than your paramater.
Please just be sure that your parameter $args['name'] is a string. I'm pretty sure it's not.
I'd bet it's an array (is_array())
Please check the $args['name'] before your while loop
Add if(isset($args['name'])) or more sure with if(!empty($args['name']))
First of all, I really don't know if that kind of topic exist. But I searched a lot and now I am here.
My question about parsing. For example I would like to unset some items.
$now = array();
$now[0]['name'] = "Hello1";
$now[0]['si'] = "BumBum1";
$now[1]['name'] = "Hello2";
$now[1]['si'] = "BumBum2";
$now[2]['name'] = "Hello3";
$now[2]['si'] = "BumBum3";
$now[3]['name'] = "Hello4";
$now[3]['si'] = "BumBum4";
echo json_encode($now)."<br>";
unset($now[0]);
echo json_encode($now);
And the output:
[{"name":"Hello1","si":"BumBum1"},{"name":"Hello2","si":"BumBum2"},{"name":"Hello3","si":"BumBum3"},{"name":"Hello4","si":"BumBum4"}]
{"1":{"name":"Hello2","si":"BumBum2"},"2":{"name":"Hello3","si":"BumBum3"},"3":{"name":"Hello4","si":"BumBum4"}}
And my the JSON file turns to messy code. Appears numbers and etc.
Any ideas how to solve this.
You need to "reindex" the array (use array_values() function).
//unset..
unset($now[0]);
//reindex
$now = array_values($now);
//display as before
echo json_encode($now);
I hope that someone can help me figure this out because it is driving me crazy. First off some background and values of the variables below.
The $TritPrice variable fluctuates as it comes from another source but for an example, lets say that the value of it is 5.25
$RefineTrit is constant at 1000 and $Minerals[$oretype][0] is 333
When I first goto the page where this code is, and this function runs for some reason the $TritPrice var either get truncated to 5.00 or gets rounded down but only during the formula itself. I can echo each of variables and they are correct but when I echo the formula and do the math manually the $TritPrice is just 5 instead of 5.25.
If I put in $TritPrice = 5.25; before the if statement it works fine and after the form is submitted and this function is rerun it works fine.
The page that uses this function is at here if yall want to see what it does.
If ($Minerals[$oretype][1] <> 0) {
$RefineTrit = getmintotal($oretype,1);
if ($RefineTrit < $Minerals[$oretype][1]) {
$NonPerfectTrit = $Minerals[$oretype][1] +
($Minerals[$oretype][1] - $RefineTrit);
$Price = (($TritPrice * $NonPerfectTrit) / $Minerals[$oretype][0]);
} else {
$Price = $TritPrice * $RefineTrit / $Minerals[$oretype][0];
}
}
This is where the $TritPrice
// Get Mineral Prices
GetCurrentMineralPrice();
$TritPrice = $ItemPrice[1];
$PyerPrice = $ItemPrice[2];
$MexPrice = $ItemPrice[3];
$IsoPrice = $ItemPrice[4];
$NocxPrice = $ItemPrice[5];
$ZydPrice = $ItemPrice[6];
$MegaPrice = $ItemPrice[7];
$MorPrice = $ItemPrice[8];
and the GetCurrentMineralPrice() function is
function GetCurrentMineralPrice() {
global $ItemPrice;
$xml = simplexml_load_file("http://api.eve-central.com/api/marketstat?typeid=34&typeid=35&typeid=36&typeid=37&typeid=38&typeid=39&typeid=40&typeid=11399&usesystem=30000142");
$i = 1;
foreach ($xml->marketstat->type as $child) {
$ItemPrice[$i] = $child->buy->max;
$i++;
}
return $ItemPrice;
}
The problem is not in this piece of code. In some other part of the program, and I suspect it is the place where the values from the textboxes are accepted and fed into the formula - in that place there should be a function or code snippet that is rounding the value of $TritPrice. Check the place where the $_POST values are being fetched and also check if any javascript code is doing a parseInt behind the scenes.
EVE-Online ftw.
with that out of the way, it's possible that your precision value in your config is set too low? Not sure why it would be unless you changed it manually. Or you have a function that is running somewhere that is truncating your variable when you call it from that function/var
However, can you please paste the rest of the code where you instantiate $TritPrice please?
Suppose that I have the PHP function as below:
function.php
<?php
function getDataInFile($PMTA_FILE){
$PMTA_DATE = date("Y-m-d");
$lineFromText = explode("\n", $PMTA_FILE);
$number_bar_charts = 13;
$row = 0;
$cate = "";
$total ="";
$fail = "";
$mailSuc = "";
$title = "";
foreach($lineFromText as $line){
if($row < $number_bar_charts){
$words = explode(";",$line);
$dateTime .= ','.$words[0];
if($title == ""){
$title = $words[0];
}
$cate .= ','."'$words[5]'";
$total .= ','.$words[6];
$fail .= ','.$words[7];
$mailSuc .= ','.((int)$words[6] - (int)$words[7]);
$row++;
}
}
}
?>
This is code below that I call the function to use in getFile.php.
<?php
include("include/function.php");
$PMTA_DATE = date("Y-m-d");
getDataInFile("../stats_domain_recepteur.affinitead.net.".$PMTA_DATE.".txt");
?>
In fact, it can not read data from the file, I got the error messages Undefined variable: dateTime in C:\wamp\www\chat\include\function.php on line 15,Notice: Undefined offset: 5 in C:\wamp\www\chat\include\function.php on line 19....
I do not know how to fix this, Anyone help me please, Thanks.
These are Notices only. They are not terrible errors that will blow up your code, but some code reviewers would make you fix them. PHP is just giving you a polite nudge, but will work anyhow. Fatal errors are the big, bad problems that will stop PHP in its tracks.
Here are the problems PHP found...
You're appending data to the string $dateTime on each iteration. On the first pass through the variable doesn't yet exist. PHP doesn't really care, but will issue a warning. To get rid of that problem, define $dateTime before you use it.
$dateTime = null;
The second problem is an array out of bounds exception. You are trying to do something with $words[5] when that array index doesn't exist. In general, you should check that array indexes, variables and other fun stuff actually exist before you try to use them.
$cate .= sprintf(",'%s'", isset($word[5]) ? $word[5] : '');
If you don't want to see Notices and Warnings reported in the error log, see PHP Error Handling to learn how to set which error levels you want to see in your log.
You should also read all about the file_get_contents function to actually get the file in the first place!
add $dateTime = ''; before foreach($lineFromText as $line){
this will works fine.
The error messages are 100% legit: you're trying to use a variable which hasn't been initialized before. Put this code above the loop and you'll get rid of this error:
$dateTime = '';
Regarding the second error - it tells that you don't have 6-th element in the array, so you'd better replace that code with a check:
$cate .= sprintf(",'%s'", isset($word[5]) ? $word[5] : '');
Extrapolate this check to other index accesses, as well.
I'm trying to parse a 6,000 line 500 KB file into an array so I can import the data into our system. The problem is that the script stops executing somewhere between lines 3000-4000. There are no breaks in the code, we use it on other imports. Any ideas on why this might be happening and what I can do to prevent it?
/**
* Takes a seperated value string and makes it an array
* #param $delimiter string The delimiter to be seperated by, usually a comma or tab
* #param $string string The string to seperate
* #return array The resulting array
*/
public function svToArray ($delimiter, $string) {
$x = 0;
$rowList = array();
$splitContent = preg_split("#\n+#", trim($string));
foreach ($splitContent as $key => $value) {
$newData = preg_split("#".$delimiter."#", $value);
if ($x == 0) {
$headerValues = array_values($newData);
} else {
$tempRow = array();
foreach ($newData as $rowColumnKey => $rowColumnValue) {
$tempRow[$headerValues[$rowColumnKey]] = $rowColumnValue;
}
$rowList[] = $tempRow;
}
$x++;
}
return $rowList;
}
UPDATE:
Error reporting is enabled. I've started using a file that's only 130KB at 1,500 lines and it does the same thing...
When I add debug code as in the following example nothing echoes at all unless I put an exit after the echo "test<br/>";
public function svToArray ($delimiter, $string) {
$x = 0;
$rowList = array();
$splitContent = preg_split("#\n+#", trim($string));
echo "test<br/>";
foreach ($splitContent as $key => $value) {
$newData = preg_split("#".$delimiter."#", $value);
if ($x == 0) {
$headerValues = array_values($newData);
} else {
$tempRow = array();
foreach ($newData as $rowColumnKey => $rowColumnValue) {
$tempRow[$headerValues[$rowColumnKey]] = $rowColumnValue;
}
$rowList[] = $tempRow;
}
$x++;
}
echo "test";
$this->tru->debug($rowList);
exit;
return $rowList;
}
UPDATE
If I comment out $tempRow[] = $rowColumnValue; then it echoes everything fine....
Probably it just timeouts. Does it always stop after X seconds?
Try setting the max execution time higher: set_time_limit(900) at the top of your pages.
You can check the max execution time in your phpinfo():
1. Create a new php page with
2. Search for max_execution_time
Have you looked at the files? Is there a line with too many delimiters? Also, what are all the "#" about?
My best guess is that you're hitting a line where $headerValues[$rowColumnKey] is not defined.
What about $rowColumnKey and $rowColumnValue ?
They are not defined in the function.
Make sure that you have error reporting set, put this on top of your php file:
ini_set('display_errors', true);
error_reporting(E_ALL);
Also you can extend the script's execution time:
ini_set('max_execution_time', 50000);
About the only time I've a php script die, with no output and no errors is when it runs out of memory. It doesn't look like your script would use much memory, but I would check to make sure that the memory limit for php is high enough.
Are you sure that you are iterating through the returned array instead of simply trying to print it? (The issue may be outside of the function rather than within it.)
Also...
`exit;
return $rowList;`
Try removing the 'exit;' line and see if that changes anything.
Also, $splitContent is not defined as an array before being used, but preg_split is going to return an array. (This should not impact your results, but it is safe to do so.)
Why are you using $key => $value pairs when you cannot be sure of what will be within the string? If we could see an small example of the content of $string, we might be able to adjust this function to work better.
The # should be replaced with /, but that may simply be a formatting issue.
$newData should be defined as an array before being used just to be safe even though that is not causing your issue.
If you can, increase maximum execution time in php.ini.. also increase the maximum memory amount for each instance.. checking error logs of your webserver could also help.
It appears as though there was too much output to the output buffer, causing the page to show nothing at all.