多個陣列,判斷鍵值是否存在從屬關係

zhaozhangxiao發表於2021-08-15
$products = array(
    ['id' => 1,'name' => 'A','catid' => 5],
    ['id' => 2,'name' => 'B','catid' => 6],
    ['id' => 3,'name' => 'C','catid' => 7],
);

$category = [
    ['id' => 5,'name' => '分類1'],
    ['id' => 6,'name' => '分類2'],
    ['id' => 99,'name' => '分類3'],
];

$new_product = [];
foreach ($products as $key => $value) {
    $new_product[$value['catid']] = $value;
}

foreach ($category as &$cate) {
    $abc = $new_product[$cate['id']] ? 1 : 0;
    if ($abc) {
        $cate['counts'] = 1;
    } else {
        $cate['counts'] = 0;
    }
}

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

相關文章