PHP:将数组乘以2并将其存储到新数组

时间:2019-07-16 10:01:59

标签: php arrays

我有空数组$one$two

$one = [];
$two = [];

我有一个名为 alpabhet 的数组。

$alphabet = ["A", "B", "C", "D"];

是否可以像这样获得数组:

$one = [
    0 => "A",
    1 => "C",
];

$two = [
    0 => "B",
    1 => "D",
];

谢谢!

3 个答案:

答案 0 :(得分:1)

您可以使用array_filter()来查看密钥是偶数还是奇数。使用常量ARRAY_FILTER_USE_KEY将键值而不是值传递给回调。这将起作用,因为您声明的数组从0开始被数字索引。

$alphabet = ["A", "B","C","D"];
$one = array_filter($alphabet, function($key) {
    return !($key & 1); // Even keys
}, ARRAY_FILTER_USE_KEY);

$two = array_filter($alphabet, function($key) {
    return $key & 1; // Odd keys
}, ARRAY_FILTER_USE_KEY);

但是,这确实保留了阵列的原始键,因此,如果要重新分配键,则可以在结果阵列上使用array_values(),请参见https://3v4l.org/jv0Od

答案 1 :(得分:1)

您可以使用modulo %运算符:

$alphabet = ["A", "B","C","D"];
$one = [];
$two = [];

foreach ($alphabet as $k => $v) {
    $k % 2 === 0 ? $one[] = $v : $two[] = $v;
}

print_r($one);
print_r($two);

结果

Array
(
    [0] => A
    [1] => C
)
Array
(
    [0] => B
    [1] => D
)

答案 2 :(得分:0)

您可以尝试像这样循环播放

$alphabet = ["A", "B", "C", "D"];

$one = [];
$two = [];


foreach ($alphabet as $key => $val) {
    if($key == 0 || ($key%2) == 0) {
        $one[] = $val;
    } else {
        $two[] = $val;
    }
}

echo "<pre>";
print_r($one);
print_r($two);