PHP - 使用另一个数组过滤数组

时间:2016-10-03 16:26:10

标签: php arrays

我正在使用2个阵列。 第一个数组来自CSV文件的数据,另一个是来自API的响应。

是否可以使用数组1中的匹配值来过滤数组2?

数组1示例

Array
(

[0] => Array
    (
        [0] => B00CEEZ57S

    )

[1] => Array
    (
        [0] => B002QJZADK

    )

[2] => Array
    (
        [0] => B001EHL2UK

    )

[3] => Array
    (
        [0] => B003FSTNB6

    )

)

数组2示例

    Array
(
    [0] => Array
    (
        [name] => Jonathan Franzen: Purity (Hardcover); 2015 Edition 
        [ASIN] => B01FMW0CJ4
    )

[1] => Array
    (
        [name] => Cardinal Gates Outdoor Child Safety Gate,  Brown
        [ASIN] => B00CE8C7SO
    )

[2] => Array
    (
        [name] => Sauder Edge Water 71.88" Bookcase Estate Black Finish
        [ASIN] => B00YAT9UGC
    )

[3] => Array
    (
        [name] => The Pioneer Woman 82695.03R Cowboy Rustic 8" Rosewood Handle Can Opener, Scis...
        [ASIN] => B015LU7GPU
    )

2 个答案:

答案 0 :(得分:3)

请尝试这个。

<?php
$arr = Array
(
    Array(
        "name" => "Jonathan Franzen: Purity (Hardcover); 2015 Edition",
        "ASIN" => "B002QJZADK"
    ),
    Array(
        "name" => "Cardinal Gates Outdoor Child Safety Gate, Brown",
        "ASIN" => "B00CE8C7SO"
    ),
    Array(
        "name" => "Sauder Edge Water 71.88' Bookcase Estate Black Finish",
        "ASIN" => "B001EHL2UK"
    )
);

$arr2 = Array(
    Array("B00CEEZ57S"),
    Array("B002QJZADK"),
    Array("B001EHL2UK")
);

$arr2Make = array();
foreach ($arr2 as $key => $a) {
    if ( isset($a[0]) ) {
        $arr2Make[] = $a[0];
    }
}


$arrMake = array_filter($arr,function($a){
    global $arr2Make;
    if ( in_array($a["ASIN"], $arr2Make) ) {
        return $a;
    }
});


print_r($arrMake);
?>

答案 1 :(得分:1)

假设两个数组分别为<xf:action ev:event="xforms-model-construct"> <xf:insert ref="instance('subInstance')" origin=" xf:element( 'subInstance', instance('defaultType')/type ) "/> </xf:action> $array1,则需要遵循以下步骤:

  1. $array2转换为1维数组$array1,因为这样更容易检查值。
  2. 使用array_filter()过滤$options,使$array2索引对应的值与'ASIN'

    中包含的值匹配
    $options