使用while循环从多个数组中检索数据

时间:2016-12-22 14:21:26

标签: php arrays

我正在寻找一种使用while循环优化以下代码的方法..我有4个数组,并希望以最有效的方式从每个数组中提取第一个值。这是原始代码,工作正常:

$arr1 = array ("55", "66", "77");
$arr2 = array ("54", "64", "771");
$arr3 = array ("53", "62", "772");
$arr4 = array ("52", "60", "773");
$x = 1;
$result = "null";

echo $arr1[0] . " | " ; 
echo $arr2[0]. " | " ; 
echo $arr3[0]. " | " ; 
echo $arr4[0]. " | " ; 

Blow是我尝试优化它,但它似乎没有起作用:

$arr1 = array ("55", "66", "77");
$arr2 = array ("54", "64", "771");
$arr3 = array ("53", "62", "772");
$arr4 = array ("52", "60", "773");
$x = 1;
$result = "null";

while($x < 5) {
$result = "$arr".$x."[0]";
echo $result;
echo " | ";
$x = $x +1;
}

我得到的输出是 1 [1] | 2 [1] | 3 [1] | 4 [1]
代替 55 | 54 | 53 | 52 |

谢谢大家!

2 个答案:

答案 0 :(得分:4)

while($x < 5) {
    $result = ${"arr".$x}[0];
    echo $result;
    echo " | ";
    $x++;
}

或更简洁的解决方案:

$arr1 = array ("55", "66", "77");
$arr2 = array ("54", "64", "771");
$arr3 = array ("53", "62", "772");
$arr4 = array ("52", "60", "773");

for($x=1; $x<5; $x++) {
    $result = ${"arr".$x}[0];
    echo $result." | ";
}

答案 1 :(得分:1)

&#34;使用call_user_func_arrayarray_column函数的单行&#34; 解决方案:

$result = implode(" | ", call_user_func_array('array_column', [[$arr1, $arr2, $arr3, $arr4], 0]));

print_r($result);

输出:

55 | 54 | 53 | 52