PHP比较两个多维和简单的数组



我有两个数组

$matchingskusarr = Array( 0 => Array(1235 => 171), 1 => Array(1235 => 172),2 => Array(180 => 200),3 => Array(180 => 807),4 => Array(125 => 200),5 => Array(131 => 200)) ;

$ordersku=数组(0=>807,1=>200,2=>171,3=>172);

function yourMatch($orderskusarr, $matchingskusarr) { 
    $columns = [];  
    foreach ($matchingskusarr as $array) {
        foreach ($array as $key => $value) {
            //Column already tested just continue
            if(isset($columns[$key])) {
                continue;
            }
            //New column we need to check if it matches our $skus
            $columns[$key] = array_column($matchingskusarr, $key);
            if($columns[$key] == $orderskusarr) {
                return [$key => $columns[$key]];                    
            } 
            else
            {           
                return $columns;            
            } 
        }   
    }       
    }
print_r(yourMatch($orderskusarr, $matchingskusarr));

**我的函数未返回正确的结果结果应该是**

Array(1235 => Array(0 => 171,1 => 172),180 => Array(0 => 803,1 => 200);

如果我正确理解你想要实现的目标,这可能对你有用。请注意,如果在$matchingskuarr中发现两次,例如200,则这些值可能会在输出中重复。为了避免这种情况(你想吗?),你需要在另一个变量中存储一个唯一值的索引。

$matchingskusarr = Array( 0 => Array(1235 => 171), 1 => Array(1235 => 172),2 => Array(180 => 200),3 => Array(180 => 807),4 => Array(125 => 200),5 => Array(131 => 200)) ;
$ordersku = array(0=>807, 1=>200,2=>171,3=>172);
$columns = [];
$uniqueSku = [];
foreach ($matchingskusarr as $array) {
    foreach ($array as $key => $value) {
        // Check for duplicity.
        if (in_array($value, $uniqueSku)) {
            continue;
        }
        // If the $value is contained in $ordersku, save it for output.
        if (in_array($value, $ordersku)) {
            // Initialize the array.
            if (!isset($columns[$key])) {
                $columns[$key] = [];
            }
            // Store the value found.
            $columns[$key][] = $value;
            $uniqueSku[] = $value;
        }
    }
}    
print_r($columns);

输出为:

Array
(
    [1235] => Array
        (
            [0] => 171
            [1] => 172
        )
    [180] => Array
        (
            [0] => 200
            [1] => 807
        )
)

相关内容

  • 没有找到相关文章

最新更新