合并一个数组键和另一个数组值PHP

时间:2017-12-25 12:37:56

标签: php arrays

我有两个数组As Follow

数组1 这是默认数组

Array
(
    [0] => pname
    [1] => minmrpprice
    [2] => maxmrpprice
    [3] => unittype
    [4] => minorder
    [5] => pdetails
    [6] => status
    [7] => product_group
    [8] => specification
)

数组2 这是动态数组

Array
(
    [pname] => Designer Dress By Textilemart
    [h1] => 1
    [userid] => textilemart
    [minmrpprice] => 1212
    [maxmrpprice] => 
    [unittype] => Piece
    [minorder] => 12
    [pdetails] => adsfadf
    [_wysihtml5_mode] => 1
    [status] => 1
    [product_group] => 2
    [addGroupInput] => 
    [categories] => 2
    [0] => 299
    [1] => 84
    [2] => 71
    [3] => 45
    [specification] => 84
    [4] => 
    [submit] => Update Product
)

现在我需要的是我想将数组1值与数组2键和

合并
  1. 仅获取在Array2中具有值的元素
  2. 删除所有其他键和值
  3. 以上示例的结果如下

    Array
    (
        [0] => pname
        [1] => minmrpprice
        //[2] => maxmrpprice(THIS DON'T SHOW BECAUSE VALUE IS EMPTY)
        [3] => unittype
        [4] => minorder
        [5] => pdetails
        [6] => status
        [7] => product_group
        [8] => specification
    )
    

    我也尝试过merge_array,但它会像我这样返回

    Array
    (
        [0] => pname
        [1] => minmrpprice
        [2] => maxmrpprice
        [3] => unittype
        [4] => minorder
        [5] => pdetails
        [6] => status
        [7] => product_group
        [8] => specification
        [pname] => Designer Dress By Textilemart
        [h1] => 1
        [userid] => textilemart
        [minmrpprice] => 1212
        [maxmrpprice] => 
        [unittype] => Piece
        [minorder] => 12
        [pdetails] => adsfadf
        [_wysihtml5_mode] => 1
        [status] => 1
        [product_group] => 2
        [addGroupInput] => 
        [categories] => 2
        [9] => 299
        [10] => 84
        [11] => 71
        [12] => 45
        [specification] => 84
        [13] => 
        [submit] => Update Product
    )
    

    我不需要这样

2 个答案:

答案 0 :(得分:2)

试试这个

循环遍历array1并使用检查array2中的值

foreach($arr1 as $a){

if(!empty($arr2[$a])){

 $new[] = $a;
  }
}

print_r($new);

答案 1 :(得分:1)

有一个函数完全符合您的要求,称为array_intersect_key,它删除数组中不作为另一个数组中的键出现的所有值。 array_intersect_key documentation

您遇到的问题是,您的第一个数组没有所需的字段作为键,而是作为值。幸运的是,有一个函数可以简单地交换这些,称为array_fliparray_flip会将所有值转换为键,将键转换为值。这仅适用于string / int值。 array_flip documentation

要构建两个数组的交集,可以使用以下代码:

$wantedKeys = array_flip($array_one);
$result = array_intersect_key($array_two, $wantedKeys);

结果将是$array_two的一部分,其中的键也出现在$wantedKeys数组中。