问题描述:
我要做的是将动态创建的变量从循环传递到php中的函数。更具体地说,我使用for循环来创建变量并为它们分配数据。然后使用for循环将所有变量串在一起。然后将字符串传递给multisort_array函数并展开字符串以使用变量。我不确定我做错了什么。
问题:
如何在不知道要创建的数量的情况下,将一堆动态创建的变量传递给排序函数?这是我的删除。
代码:
$arr2[0] = "100::HOMEDEPOT";
$arr2[1] = "200::WALMART";
$arr2[2] = "300::COSTCO";
$arr2[3] = "400::WALGREENS";
$arr2[4] = "500::TACO BELL";
// explodes first value of $arr2
$tmp = explode("::",$arr2[0]);
// determines how many dynamic variables to create
for($k=0;$k<count($tmp);$k++){
${"mArr".$k} = Array();
}
// loops thru & assigns all numbers to mArr0
// loops thru & assigns all names to mArr1
for ($k=0;$k<count($arr2);$k++){
$tmp = explode("::",$arr2[$k]);
for($l=0;$l<count($tmp);$l++){
${"mArr".$l}[$k] = $tmp[$l];
}
}
// Will add a for loop to combine the variables into string
$param = "$mArr1,$mArr0";
// send the string to array_multisort to be sorted by name
// have tried the following options:
// 1. array_multisort(explode(",",$param));
// 2. call_user_func_array(array_multisort,explode(",",$param));
// both do not sort & give me an error.
提前感谢您的帮助。我对其他可以实现的方法有任何建议,但我希望它尽可能在PHP代码中。
答案 0 :(得分:0)
将数组本身传递给函数。
arraySort($array);
答案 1 :(得分:0)
$arr2[0] = "100::HOMEDEPOT";
$arr2[1] = "200::WALMART";
$arr2[2] = "300::COSTCO";
$arr2[3] = "400::WALGREENS";
$arr2[4] = "500::TACO BELL";
//Split the input in place, you could also use a new array for this
for($i = 0;$i < count($arr2);$i++)
{
$arr2[$i] = explode("::",$arr2[$i]);
}
//Define our new sorting function
function sort_second_item($a,$b)
{
return strcmp($a[1],$b[1]);
}
var_dump($arr2);
usort($arr2,'sort_second_item');
var_dump($arr2);
$rotated = array();
//Rotate $arr2
for($i = 0; $i < count($arr2); $i++)
{
for($j = 0;$j < count($arr2[$i]); $j++)
{
if(!isset($rotated[$j]))
{
$rotated[$j] = array();
}
$rotated[$j][$i] = $arr2[$i][$j];
}
}
var_dump($rotated);