看到演算法問題很有意思,這邊用最笨方法解!

wozailu發表於2021-07-22

原文地址

  • 不保證是對的
<?php

$array = [1, 2, 3, 4, 5, 6, 7, 8];        // 要買的東西的陣列

// 超市所擁有的商品
$lists = [
    'a' => [7, 8, 6, 2, 4],
    'b' => [7, 1, 2, 3],
    'c' => [4, 5, 6, 8],
    'd' => [6, 7, 8, 1],
    'e' => [3, 5, 8]
];


// 儲存元素位置
$items = [];

// 購買的東西在超市位置
foreach ($array as $key => $value) {
    $it = [
        'value' => $value,
        'list' => [],
    ];
    foreach ($lists as $kk => $vv) {
        if (in_array($value, $vv)) {
            $it['list'][] = $kk;
        }
    }
    $items[] = $it;
}

/*
    每件商品追加
    比如 
    a 1
    b 1 2

    變成
    a-1 b-1
    a-1 b-2
*/ 
$find = [];
$i = 0;
$allCount = count($items);
foreach ($items as $ki => $vi) {
    $before = [];
    if ($allCount != $i) {
        $before = $find;
    }
    $find = [];
    if ($i == 0) {
        foreach ($vi['list'] as $kik => $viv) {
            $isss = $viv . '-' . $vi['value'];
            $find[] = $isss;
        }
    }
    if ($i == 1) {
        foreach ($vi['list'] as $kik => $viv) {
            $isss = $viv . '-' . $vi['value'];
            foreach ($before as $k1 => $v1) {
                $find[] = [$v1, $isss];
            }
        }
    }
    if ($i > 1) {
        foreach ($vi['list'] as $kik => $viv) {
            $isss = $viv . '-' . $vi['value'];
            foreach ($before as $k2 => $v2) {
                $kss = [$isss];
                foreach ($v2 as $k3 => $v3) {
                    $kss[] = $v3;
                }
                $find[] = $kss;
            }
        }
    }

    $i++;
}

// 資料分類匯出
$ress = [];
foreach ($find as $kf => $vf) {
    $item = [];
    foreach ($vf as $k3 => $v3) {
        $ks3 = explode('-', $v3);
        $item[$ks3[0]][] = $ks3[1];
    }
    $ress[] = $item;
}

var_dump($ress);
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章