是否可以从php中的每个数组打印特定位置值?

时间:2019-05-25 20:41:46

标签: php arrays

我在php中有一些数组。我想从每个数组的特定位置打印特定值。例如,如果我想从每个数组中打印第二个值,那么php中的功能是什么?

$firstArray = array("Saif", "Website Development", "Senior");

$secondArray = array("Rifat", 25, "Mentor");

$thirdArray = array("Fahim", "Elder Brother", "PreCadet School");

3 个答案:

答案 0 :(得分:2)

return

给出输出:

<?php

$firstArray = array("Saif", "Website Development", "Senior");
$secondArray = array("Rifat", 25, "Mentor");
$thirdArray = array("Fahim", "Elder Brother", "PreCadet School");

function printPosition($position)
{
    $arguments = func_get_args();
    array_shift($arguments);

    foreach($arguments as $argument) {
        $keys = array_keys($argument);
        if(isset($keys[$position])) {
            echo $argument[$keys[$position]] . '<br>' . PHP_EOL;
        }
    }
}

printPosition(1, $firstArray, $secondArray, $thirdArray);

需要注意的是,当一个或多个数组具有非数字键时,该解决方案也适用。

例如这些数组:

Website Development<br>
25<br>
Elder Brother<br>

您仍然得到相同的结果:

$firstArray = array("Saif", "second" => "Website Development", "Senior");
$secondArray = array("first" => "Rifat", 25, "Mentor");
$thirdArray = array("boo" => "Fahim", "moo" => "Elder Brother", "third" => "PreCadet School");

答案 1 :(得分:0)

将所有阵列添加到一个阵列后,请使用array_column。

$firstArray = array("Saif", "Website Development", "Senior");

$secondArray = array("Rifat", 25, "Mentor");

$thirdArray = array("Fahim", "Elder Brother", "PreCadet School");

$arr = [$firstArray, $secondArray, $thirdArray];

echo implode(", ", array_column($arr, 1));

这将以逗号间隔作为分隔符,回显数组的第二列。

https://3v4l.org/6Q1JQ

答案 2 :(得分:0)

您可以使用自定义的functionarray_column

$firstArray = array("Saif", "Website Development", "Senior");
$secondArray = array("Rifat", 25, "Mentor");
$thirdArray = array("Fahim", "Elder Brother", "PreCadet School");
function getValuesByPosition($position, ...$arr){ //Splat operator
    $res=[];
    foreach($arr as $key => $value){
      $res[] = $value[$position];
    }
    return $res;
}
$result = getValuesByPosition(1,$firstArray,$secondArray,$thirdArray);

OR

使用array_column作为@andreas解决方案。