将multidimentional数组与简单数组进行比较

时间:2016-07-09 10:23:27

标签: php arrays

我有两个数组我想比较这两个数组并找到匹配。如果807和200出现在131之类的相同键中,则创建第三个数组

array(131=>(807,200));

ARRAY1: -

Array([0] => 807,[1] => 200)

array2: -

$mat= Array([0] => Array([131] => 807),[1] => Array([132] => 807),[2] => Array([125] => 200),[3] => Array([131] => 200)) 

我的代码:

<?php
$filtered = array();
array_walk_recursive($matchingskusarr, function($val, $key) use(&$filtered) {
    if ($key === 131) {
        echo "The key $key has the value $val<br>";
        $filtered[$val] = $key;
    }
});

echo "<pre>";
print_r($filtered);
echo "</pre>";
?>

1 个答案:

答案 0 :(得分:0)

您可以像这样使用array_column

$filtered = array_column($mat, 131);
//Output: Array ( [0] => 807 [1] => 200 )

更新1:

$matchingskusarr = Array( 0 => Array(131 => 807), 1 => Array(132 => 807),2 => Array(125 => 200),3 => Array(131 => 200)) ;
$skus = array(0=>807, 1=>200);


function yourMatch($skus, $matchingskusarr) {
    $continue = [];
    foreach ($matchingskusarr as $array) {
        //Get the first key !!!
        foreach ($array as $key => $value);
        //Column already tested just continue
        if(isset($continue[$key])) {
            continue;
        }
        //New column we need to check if it matches our $skus
        $column = array_column($matchingskusarr, $key);
        if($column  == $skus) {
            return [$key => $column ];
        }
        $continue[$key] = true;
    }
    return null;     
}

print_r(yourMatch($skus, $matchingskusarr));

演示: https://3v4l.org/Cr2L4