0

有没有更好的方法来做这样的事情?这很好,但我认为可能有一条捷径可以得到相同的结果。我想很容易添加更多的数组,我可以把它变成一个函数,然后在它外面有 for 循环,但仍然如此。

就是想。

<?
$array1 = array("test1","test2","test3","test4");
$array2 = array("dest1","test2","dest3","dest4");




    for ($i=0; $i<count($array1); $i++) { //FOR STATEMENT TO GET MULTIPLE ARRAYS REGISTERED AS A FOREACH-STYLE 
    $val1 = $array1[$i]; //VALUES GET
    $val2 = $array2[$i];

    $array1 = array_flip($array1); //ARRAY IS FLIPPED FROM KEY => VALUE TO VALUE => KEY SO THAT THE KEYS CAN BE GET. REMEMBER TO SWITCH IT BACK.
    $array2 = array_flip($array2);

    $key1 = $array1[$val1]; //NOW MUST ITERATE THROUGH USING VALUES ABOVE BECAUSE THE KEYS ARE NO LONGER NUMBERS.
    $key2 = $array2[$val2];

    $array1 = array_flip($array1); //SWITCHING IT BACK.
    $array2 = array_flip($array2);

    echo $key1 . "=>" . $val1 . "<br />";
    echo $key2 . "=>" . $val2 . "<br />";

    }




    var_dump($array1);

    ?>
4

2 回答 2

1

您已经有了数组的“键”,$i.

for ($i=0; $i<count($array1); $i++) {
    $val1 = $array1[$i]; // You're getting the value from the array,
    $val2 = $array2[$i]; // you already have the key, $i

    echo $i . "=>" . $val1 . "<br />";
    echo $i . "=>" . $val2 . "<br />";
}

编辑:如果两个数组具有相同的键,你可以foreach超过一个,并从另一个获取值。

foreach($array1 as $key=>$val1){
    $val2 = $array2[$key];

    echo $key . "=>" . $val1 . "<br />";
    echo $key . "=>" . $val2 . "<br />";
}
于 2012-04-02T21:47:48.727 回答
1

目前我能做到的最好的

$arrayList = Array($array1, $array2); // Add every array here
$keyArr = Array();
foreach ($arrayList as $key => $value)
{
   // Put the keys of every array in $arrayList in an other array
   $keyArr[$key] = array_keys($value);
}
// Loop while $i is lower than the highest index of the bigest array in $arrayList
for ($i = 0; $i < count(max($arrayList )); $i++)
{
   // Loop every array in $arrayList
   foreach ($arrayList as $arrKey => $arr)
   {
     // If the array in $arrayList has at least $i element
     if ($i < count($arr))
     {

       // Get the key of the $i-n element in the array (take it from the $keyArr defined above)
       $key = $keyArr[$arrKey][$i];
       // Get the value of the $i-n element in the array
       $val = $arr[$key];
     }
   }
}
于 2012-04-02T21:56:29.857 回答