PHP:将动态创建的变量传递给内置函数


PHP: Pass dynamically created variables to a built-in function

问题描述:
我试图做的是将动态创建的变量从循环传递到php中的函数。更具体地说,我使用 for 循环来创建变量并为它们分配数据。然后使用 for 循环将所有变量串在一起。然后将字符串传递给 multisort_array 函数并分解字符串以使用变量。我不确定我做错了什么。

QUESTION:
如何在不知道要创建多少变量的情况下将一堆动态创建的变量传递给排序函数?这就是我的德勒玛。

代码:

$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 代码中。

只需将数组本身传递到函数中即可。

arraySort($array);

在使用自定义排序函数将其拆分为其他数组之前对数组进行排序:

$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);