Below I have a segment of my code that I recently added to my PHP, which takes an array of integers ($naEUS) and iterates though it, appending the numbers with commas in between with a few exceptions for the start and finish. The end result should be a string that looks like this: ( ### , ### , ### , ### )
$num = count( $naEUS[$f] );
$re开发者_如何学JAVAsultsFields_values = "(";
for( $b = 0; $b < $num; $b++ )
{
if( $b = 0 )
{
$resultsFields_values = substr_replace( $resultsFields_values, " {$naEUS[$b]} " , ( strlen($resultsFields_values) ), 0);
}
$resultsFields_values = substr_replace( $resultsFields_values, ", {$naEUS[$b]} " , ( strlen($resultsFields_values) ), 0);
}
$resultsFields_values = substr_replace( $resultsFields_values, ")" , ( strlen($resultsFields_values) ), 0);
I realize there are plenty of threads addressing string concatenation, but they only address part of my problem. I know this is a horribly inefficient way of doing this. and they show a better way of doing it, but that's easy to find.
What I really want to know is why it took my 5 second run time PHP to it's 30 second timeout.
Of course, better solutions are also welcome.
for( $b = 0; $b < $num; $b++ )
if( $b = 0 )
With $b = 0
, you're resetting the loop back to zero on every iteration. =
is for assignment, ==
is for equality testing.
Well, it depends on the size of the array, but what you're doing here is reallocating that string in every iteration using a rather inefficient function. This will probably work fine as long as your array is small, but when it contains a couple of thousands of items, it's not wonder that execution takes long.
A better solution would be to use the implode function, like this:
$resultFields_values = '(' . implode(' , ', $naEUS) . ')';
Use comparison operator == instead of $b = 0.
精彩评论