这是我的阵列:
$arr = array("pic0", "pic1", "pic2", "pic3", "pic4");
我如何获得以下字符串:
$str1 = "pic1,pic2,pic3,pic4,pic0";
$str2 = "pic0,pic2,pic3,pic4,pic1";
$str3 = "pic0,pic1,pic3,pic4,pic2";
$str4 = "pic0,pic1,pic2,pic4,pic3";
$str5 = "pic0,pic1,pic2,pic3,pic4";
答案 0 :(得分:1)
下面的代码采用数组并在给定索引的情况下对其进行排序。 并返回一个逗号分隔的字符串与数组项。 例如,此代码将采用第1个元素[0]" pic0"并把它放在字符串的末尾。
返回一串" pic1,pic2,pic3,pic4,pic0"
$arr = array("pic0", "pic1", "pic2", "pic3", "pic4");
echo sort_by_index_to_string(0, $arr);
function sort_by_index_to_string($num, $arr)
{
$v = $arr[$num];
unset($arr[$num]);
$arr[$num] = $v;
return implode(",", $arr);
}
答案 1 :(得分:1)
我使用数组,而不是五个字符串:
$arr = array ("pic0", "pic1", "pic2", "pic3", "pic4");
$final = array ();
for($i=1, $c = count($arr); $i <= $c; ++$i) // loop n times
{
$tmp = $arr; // tmp array
$x = $arr[$i-1]; // get element to put in the end
unset($tmp[$i-1]); // unset from the tmp array
$final[$i] = implode(",", $tmp) . "," . $x; // concatenate the array with $x in the end
}
print_r($final);
/*
Array
(
[1] => pic1,pic2,pic3,pic4,pic0
[2] => pic0,pic2,pic3,pic4,pic1
[3] => pic0,pic1,pic3,pic4,pic2
[4] => pic0,pic1,pic2,pic4,pic3
[5] => pic0,pic1,pic2,pic3,pic4
)
*/