问题
I have the following code that is not returning as I expected. I was hoping the final result would be a string:
$organizers = array_unique($organizers); // this returns correctly
$organizers = implode(', ', $organizers); // this returns nothing
var_dump($organizers); // no data appears here
exit;
The array_unique()
function is returning data correctly and I can see the array it returns. To start, the $organizers
array is a simple 1-D array of strings that all have small lengths under 20 chars. I think the issue might be that $organizers
is more than 10,000 indices long. Are there limitations on the length of an array that can be imploded? Are there work-arounds for that? I cannot find anything in the manual, but I have tested this code thoroughly and I believe the error must be on implode()
.
回答1:
I dont' know if there is a limitation, but what comes to my mind is taht you are also transforming an array into a string. This shouldn't be the problem in PHP, but try calling it a different variable for the result of implode?
$organizers = array_unique($organizers); // this returns correctly
$organizers_string = implode(', ', $organizers); // this returns nothing
// This gives it a different space
回答2:
Edit: And if for some reason implode() is still problematic.
$organizers = array_unique($organizers);
$neworganizers = "";
for($i = 0; $i < sizeof($organizers); $i++)
{
$neworganizers .= $organizers[$i];
if($i != sizeof($organizers) - 1)
{
$neworganizers .= ", ";
}
}
//$neworganizers is now the equivalent of what .implode() should return when called on $organizers
$organizers = array();
$organizers[0] = "value1";
$organizers[1] = "value2";
$organizers[2] = "value3";
$organizers[3] = "value3";
$organizers = array_unique($organizers); // strips out last index
$organizers = implode(', ', $organizers); // returns string of "value1, value2, value3"
echo $organizers;
This seemed to work on writecodeline.com/php/
I've also experienced issues with older php builds when I've tried to explode/implode by a string with special characters in it and they were encapsulated by single quotes. I know it sounds crazy, but the double quotes might be necessary on some servers.
Reference: personal experience doing work on older production servers.
回答3:
I'd hate to think I'm stating the obvious, but doesn't implode only take a string as an argument? Maybe it should be something more like this...
$organizers = array_unique($organizers);
//I'm guessing what you wanted was an array of arrays?
$neworganizers = array();
for($i = 0; $i < sizeof($organizers); $i++)
{
$neworganizers[$i] = implode(", ", $organizers);
}
print_r($neworganizers);
来源:https://stackoverflow.com/questions/13845927/possible-limitation-of-implode-function-in-php