php - 如何将两个关联数组添加到同一个数组键

时间:2017-09-18 13:17:55

标签: php arrays

我想在相同的数组键中添加两个关联数组,或者只从数组中取出我需要的键,如下例所示,我在字段数组$field = [a,b];中需要的键。

假设我有阵型:

array1 = Array
(
    [key1] => Array
        (
            [a] => a
            [b] => b
            [c] => c
        )

    [key2] => Array
        (
            [a] => a
            [b] => b
            [c] => c
        )

)

$field = [a,b];
$x = [];

foreach ($array1 as $key) {
    foreach ($fields as $field) {
        $x[$key['id']] = array($field => $key[$field]);
      }
}
print_r($x);

输出:

Array
(
    [key1] => Array
        (
            [b] => b
        )

    [key2] => Array
        (
            [b] => b
        )

)

我需要:

Array
(
    [key1] => Array
        (
            [a] => a
            [b] => b
        )

    [key2] => Array
        (
            [a] => a
            [b] => b
        )

)

3 个答案:

答案 0 :(得分:0)

你可以这样做,通过仅使用$field数组中的键重建另一个多维。

以下是代码:

$field = array('a','b');
$x     = array();

foreach ($array1 as $k => $key) {
    foreach ($fields as $k2 => $field) {
        if(in_array($k2, $field))
            $x[$k][$k2] = $field;
    }
}

print_r($x);

答案 1 :(得分:0)

<?php

$arr = array(
    'key1'=>array('a'=>'a','b'=>'b','c'=>'c'),
    'key2'=>array('a'=>'a','b'=>'b','c'=>'c'),
    'key3'=>array('c'=>'c')
);

$include = array('a','b');

foreach($arr as &$res)
{
    $res = array_filter($res, function($key) use ($include) {
            return in_array($key, $include);
    }, ARRAY_FILTER_USE_KEY);
}
unset($res);

print_r($arr);

?>

测试结果

[akshay@localhost tmp]$ php test.php
Array
(
    [key1] => Array
        (
            [a] => a
            [b] => b
        )

    [key2] => Array
        (
            [a] => a
            [b] => b
        )

    [key3] => Array
        (
        )

)

答案 2 :(得分:0)

基本上你每次都要分配一个新的数组,你需要做的就是下面的代码,你只需要分配新的索引而不是数组。

<?php $array1 = array(
'key1' => array
    (
        'a' => "a",
        'b' => "b",
        'c' => "c"
    ),
'key2' => array
    (
        'a' => "a",
        'b' => "b",
        'c' => "c"
    )

);

$fields = array('a','b');
$x = [];

foreach ($array1 as $key => $value) {

    foreach ($fields as $field) {
        if(array_key_exists($field,$array1[$key]))
            $x[$key][$field] = $value[$field];
    }
}
print_r($x);